刪除聊天室

本指南說明如何針對 Google Chat API 的 Space 資源,使用 delete 方法刪除不再需要的已命名聊天室。刪除聊天室也會刪除其中的所有內容,包括訊息和附件。

必要條件

Python

  • Python 3.6 以上版本
  • pip 套件管理工具
  • 最新的 Python 專用 Google 用戶端程式庫。如要安裝或更新,請在指令列介面中執行下列指令:

    pip3 install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib oauth2client
    
  • 已發布的 Chat 應用程式。如要建立及發布 Chat 應用程式,請參閱「建構 Google Chat 應用程式」。

  • 已設定 Chat 應用程式的授權。如要刪除聊天室,就必須請具備 chat.delete 授權範圍的使用者 (須具備 chat.delete 授權範圍才能刪除指定聊天室)。

刪除已命名聊天室

如要刪除 Google Chat 中的現有聊天室,請在要求中傳入以下內容:

刪除聊天室的方法如下:

Python

  1. 在工作目錄中,建立名為 chat_space_delete.py 的檔案。
  2. chat_space_delete.py 中加入下列程式碼:

    import os.path
    
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    
    # 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()
    
  3. 將程式碼中的 SPACE 替換為聊天室名稱,該名稱可從 Chat API 的 spaces.list 方法或聊天室網址取得。

  4. 在工作目錄中建構並執行範例:

    python3 chat_space_delete.py
    

如果成功,回應主體會是空白的,表示聊天室已刪除。