在 Google Chat 中建立命名聊天室

本指南說明如何使用 Google Chat API 的 Space 資源中的 create() 方法,建立具名聊天室。

具名聊天室 (顯示 spaceType 圖示 SPACE) 是用來傳送訊息、共用檔案及協作的空間。具名聊天室可包含 Chat 擴充應用程式。具名聊天室有聊天室管理員,可套用管理設定、說明,以及新增或移除使用者和應用程式。

如要建立不同類型的 Chat 聊天室 (包括即時訊息或群組訊息),請使用 Space 資源的 setUp() 方法建立聊天室,並同時新增成員。詳情請參閱「設定空間」一文。

建立具名聊天室後,只有經過驗證的使用者會成為聊天室成員。如要將成員加入聊天室,請針對要加入的每位使用者或應用程式,呼叫 Membership 資源的 create() 方法。或者,您可以使用 setUp() 方法建立具名空間,並同時新增成員。

必要條件

Node.js

Python

Java

Apps Script

以使用者身分建立具名空間

如要建立具名的空間並驗證使用者,請在要求中傳遞下列項目:

  • 指定 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 Script

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}IDAdmin SDK 客戶資源。如要在與 Chat 應用程式相同的 Google Workspace 機構中建立聊天室,請使用 customers/my_customer
  4. 在工作目錄中,建構並執行範例:

    python3 chat_space_create_named_app.py

在 Google Chat 中開啟聊天室

如要前往該空間,請使用空間的資源 ID 建構空間的網址。您可以在 Google Chat 回應主體中找到聊天室的資源 ID name。舉例來說,如果聊天室的 namespaces/1234567,您可以使用下列網址前往該聊天室:https://mail.google.com/chat/u/0/#chat/space/1234567

限制和注意事項

  • 使用應用程式驗證建立聊天室時,通過驗證的 Chat 應用程式會新增為聊天室成員,但與使用者驗證不同,不會新增為聊天室管理員。根據預設,所有聊天室成員都可以移除 Chat 應用程式。如要只允許聊天室管理員移除 Chat 應用程式,請將 permissionSettings.manageApps 設為 managersAllowed