更新聊天室

本指南介绍了如何使用 Google Chat API 的 Space 资源中的 patch() 方法更新聊天室。更新聊天室以更改聊天室的相关属性,例如其面向用户的显示名称、说明和准则。

如果您是 Google Workspace 管理员,可以调用 patch() 方法来更新 Google Workspace 组织中的任何现有聊天室。

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

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

前提条件

Node.js

Python

Java

Apps 脚本

以用户身份更新空间

如需使用用户身份验证更新 Google Chat 中的现有聊天室,请在请求中传递以下内容:

  • 指定 chat.spaces 授权范围。
  • 调用 UpdateSpace() 方法。在请求中,您需要指定空间 name 字段、包含一个或多个要更新的字段的 updateMask 字段,以及包含更新后的空间信息的 body

您可以更新显示名称、会议室类型、历史记录状态等。如需查看您可以更新的所有字段,请参阅参考文档

以下是如何更新现有空间的 displayName 字段:

Node.js

chat/client-libraries/cloud/update-space-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';  const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.spaces'];  // This sample shows how to update a 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: {       // Replace SPACE_NAME here       name: 'spaces/SPACE_NAME',       displayName: 'New space display name'     },     // The field paths to update. Separate multiple values with commas or use     // `*` to update all field paths.     updateMask: {       // The field paths to update.       paths: ['display_name']     }   };    // Make the request   const response = await chatClient.updateSpace(request);    // Handle the response   console.log(response); }  main().catch(console.error);

Python

chat/client-libraries/cloud/update_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"]  # This sample shows how to update a space with user credential def update_space_with_user_cred():     # Create a client     client = create_client_with_user_credentials(SCOPES)      # Initialize request argument(s)     request = google_chat.UpdateSpaceRequest(         space = {             # Replace SPACE_NAME here             'name': 'spaces/SPACE_NAME',             'display_name': 'New space display name'         },         # The field paths to update. Separate multiple values with commas.         update_mask = 'displayName'     )      # Make the request     response = client.update_space(request)      # Handle the response     print(response)  update_space_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/UpdateSpaceUserCred.java
import com.google.chat.v1.ChatServiceClient; import com.google.chat.v1.UpdateSpaceRequest; import com.google.chat.v1.Space; import com.google.protobuf.FieldMask;  // This sample shows how to update space with user credential. public class UpdateSpaceUserCred {    private static final String SCOPE =     "https://www.googleapis.com/auth/chat.spaces";    public static void main(String[] args) throws Exception {     try (ChatServiceClient chatServiceClient =         AuthenticationUtils.createClientWithUserCredentials(           ImmutableList.of(SCOPE))) {       UpdateSpaceRequest.Builder request = UpdateSpaceRequest.newBuilder()         .setSpace(Space.newBuilder()           // Replace SPACE_NAME here.           .setName("spaces/SPACE_NAME")           .setDisplayName("New space display name"))         .setUpdateMask(FieldMask.newBuilder()           // The field paths to update.           .addPaths("display_name"));       Space response = chatServiceClient.updateSpace(request.build());        System.out.println(JsonFormat.printer().print(response));     }   } }

Apps 脚本

chat/advanced-service/Main.gs
/**  * This sample shows how to update a space with user credential  *   * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.spaces'  * referenced in the manifest file (appsscript.json).  */ function updateSpaceUserCred() {   // Initialize request argument(s)   // TODO(developer): Replace SPACE_NAME here   const name = 'spaces/SPACE_NAME';   const space = {     displayName: 'New space display name'   };   // The field paths to update. Separate multiple values with commas or use   // `*` to update all field paths.   const updateMask = 'displayName';    // Make the request   const response = Chat.Spaces.patch(space, name, {     updateMask: updateMask   });    // Handle the response   console.log(response); }

如需运行此示例,请将 SPACE_NAME 替换为空间 name 字段中的 ID。您可以通过调用 ListSpaces() 方法或从空间的网址中获取 ID。

Google Chat API 会返回一个反映更新的 Space 实例。

以 Google Workspace 管理员身份更新聊天室

如果您是 Google Workspace 管理员,可以调用 UpdateSpace() 方法来更新 Google Workspace 组织中的任何聊天室。

如需以 Google Workspace 管理员身份调用此方法,请执行以下操作:

  • 使用用户身份验证调用该方法,并指定支持使用管理员权限调用该方法的授权范围
  • 在请求中,将查询参数 useAdminAccess 指定为 true

如需了解详情和示例,请参阅以 Google Workspace 管理员身份管理 Google Chat 聊天室

以 Chat 应用的身份更新聊天室

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

如需使用应用身份验证更新 Google Chat 中的现有聊天室,请在请求中传递以下内容:

  • 指定 chat.app.spaces 授权范围。 通过应用身份验证,您只能更新由 Chat 应用创建的聊天室。
  • Space 资源调用 patch 方法。在请求中,您需要指定空间 name 字段、包含一个或多个要更新的字段的 updateMask 字段,以及包含更新后的空间信息的 body

您可以更新显示名称、空间类型、历史记录状态、权限设置等。如需查看您可以更新的所有字段,请参阅参考文档

编写调用 Chat API 的脚本

以下是如何更新现有空间的 spaceDetails 字段:

Python

  1. 在工作目录中,创建一个名为 chat_space_update_app.py 的文件。
  2. chat_space_update_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"]  def main():     '''     Authenticates with Chat API using app authentication,     then updates the specified space description and guidelines.     '''      # 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().patch(        # The space to update, and the updated space details.       #       # Replace {space} with a space name.       # Obtain the space name from the spaces resource of Chat API,       # or from a space's URL.       name='spaces/SPACE',       updateMask='spaceDetails',       body={          'spaceDetails': {           'description': 'This description was updated with Chat API!',           'guidelines': 'These guidelines were updated with Chat API!'         }        }      ).execute()      # Prints details about the updated space.     print(result)  if __name__ == '__main__':     main() 
  3. 在代码中,替换以下内容:

    • SPACE,其中包含聊天室名称,您可以通过 Chat API 中的 spaces.list 方法或从聊天室的网址获取该名称。
  4. 在工作目录中,构建并运行示例:

    python3 chat_space_update_app.py

Google Chat API 会返回一个反映更新的 Space 资源实例。

限制和注意事项