本指南介绍了如何在 Google Chat API 的 Space
资源中使用 delete
方法删除不再需要的命名聊天室。删除聊天室会同时删除其中包含的所有内容,包括消息和附件。
Space
资源代表用户和 Chat 应用可以发送消息、共享文件以及开展协作的地方。聊天室分为以下几种类型:
- 私信 (DM) 是两位用户或一位用户与一个 Chat 应用之间的对话。
- 群聊是指三个或更多用户与 Chat 应用之间的对话。
- 已命名聊天室是用户在其中发送消息、共享文件和开展协作的永久性位置。
前提条件
Python
- Python 3.6 或更高版本
- pip 软件包管理工具
适用于 Python 的最新 Google 客户端库。如需安装或更新它们,请在命令行界面中运行以下命令:
pip3 install --upgrade google-api-python-client google-auth-oauthlib
- 一个启用了并配置了 Google Chat API 的 Google Cloud 项目。如需了解相关步骤,请参阅构建 Google Chat 应用。
为 Chat 应用配置授权。删除聊天室需要有权删除指定聊天室的用户在
chat.delete
授权范围内进行用户身份验证。
Node.js
- Node.js 和 npm
适用于 Node.js 的最新 Google 客户端库。如需安装这些软件包,请在命令行界面中运行以下命令:
npm install @google-cloud/local-auth @googleapis/chat
- 一个启用了并配置了 Google Chat API 的 Google Cloud 项目。如需了解相关步骤,请参阅构建 Google Chat 应用。
为 Chat 应用配置授权。删除聊天室需要有权删除指定聊天室的用户在
chat.delete
授权范围内进行用户身份验证。
删除已命名的聊天室
如需删除 Google Chat 中的现有聊天室,请在请求中传递以下内容:
删除聊天室的方法如下:
Python
- 在您的工作目录中,创建一个名为
chat_space_delete.py
的文件。 在
chat_space_delete.py
中添加以下代码:from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.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.delete"] def main(): ''' Authenticates with Chat API via user credentials, then deletes the specified space. ''' # Authenticate with Google Workspace # and get user authorization. flow = InstalledAppFlow.from_client_secrets_file( 'client_secrets.json', SCOPES) creds = flow.run_local_server() # Build a service endpoint for Chat API. chat = build('chat', 'v1', credentials=creds) # Use the service endpoint to call Chat API. result = chat.spaces().delete( # The space to delete. # # 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' ).execute() # Print Chat API's response in your command line interface. # When deleting a space, the response body is empty. print(result) if __name__ == '__main__': main()
在代码中,将
SPACE
替换为聊天室名称,您可以通过 Chat API 中的spaces.list
方法或聊天室的网址获取该名称。在您的工作目录中,构建并运行示例:
python3 chat_space_delete.py
Node.js
- 在您的工作目录中,创建一个名为
delete-space.js
的文件。 在
delete-space.js
中添加以下代码:const chat = require('@googleapis/chat'); const {authenticate} = require('@google-cloud/local-auth'); /** * Deletes a Chat space. * @return {!Promise<!Object>} */ async function deleteSpace() { const scopes = [ 'https://www.googleapis.com/auth/chat.delete', ]; const authClient = await authenticate({scopes, keyfilePath: 'client_secrets.json'}); const chatClient = await chat.chat({version: 'v1', auth: authClient}); return await chatClient.spaces.delete({name: 'spaces/SPACE'}); } deleteSpace().then(console.log);
在代码中,将
SPACE
替换为聊天室名称,您可以通过 Chat API 中的spaces.list
方法或聊天室网址获取该名称。在您的工作目录中,运行示例:
node delete-space.js
如果成功,响应正文将为空,这表示已删除空格。