更新使用者和#39 的聊天室讀取狀態

本指南說明如何在 Google Chat API 的 SpaceReadState 資源上使用 updateSpaceReadState 方法,將聊天室標示為已讀或未讀。

SpaceReadState 資源是單例資源,代表指定使用者在 Google 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.users.readstate 授權範圍的使用者驗證

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.users.readstate 授權範圍的使用者驗證

Apps Script

  • 擁有可存取 Google ChatGoogle Workspace 帳戶。
  • 已發布的 Chat 應用程式。如要建構 Chat 應用程式,請按照這個quickstart操作。
  • 已針對 Chat 應用程式設定授權。如要取得聊天室內使用者的讀取狀態詳細資料,必須使用 chat.users.readstate 授權範圍的使用者驗證

更新發出呼叫的使用者的空間讀取狀態

如要在聊天室中更新使用者的讀取狀態,請在要求中加入以下內容:

  • 指定 chat.users.readstate 授權範圍。
  • 呼叫 SpaceReadState 資源上的 updateSpaceReadState 方法
  • 傳遞要取得的聊天室讀取狀態 name,包括使用者 ID 或別名,以及聊天室 ID。取得空間讀取狀態僅支援取得發出呼叫的使用者讀取狀態,可透過設定下列其中一項方式指定:
    • me 別名。例如 users/me/spaces/SPACE/spaceReadState
    • 發出呼叫的使用者的 Workspace 電子郵件地址。例如 users/user@example.com/spaces/SPACE/spaceReadState
    • 發出呼叫的使用者的使用者 ID。例如 users/USER/spaces/SPACE/spaceReadState
  • 傳遞 updateMask,指定要更新的空間讀取狀態面向,可支援下列欄位路徑:
    • lastReadTime:使用者空間讀取狀態更新的時間。通常這會對應至最後一則已讀訊息的時間戳記,或是使用者指定的時間戳記,以標示聊天室中的上次讀取位置。如果 lastReadTime 在最新的訊息建立時間之前,UI 中就會顯示該聊天室為未讀取。如要將聊天室標示為已讀,請將 lastReadTime 設為晚於最新訊息建立時間的任何值。lastReadTime 將強製配合最新的訊息建立時間。請注意,聊天室讀取狀態只會影響在聊天室頂層對話中顯示的訊息讀取狀態。執行緒中的回覆不會受到此時間戳記的影響,而是依賴執行緒讀取狀態。

以下範例會更新發出呼叫的使用者的空間讀取狀態:

Python

  1. 在工作目錄中,建立名為 chat_spaceReadState_update.py 的檔案。
  2. chat_spaceReadState_update.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.users.readstate"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then updates the space read state for the calling user.
        '''
    
        # 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.users().spaces().updateSpaceReadState(
    
            # The space read state to update.
            #
            # Replace USER with the calling user's ID, Workspace email,
            # or the alias me.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            name='users/me/spaces/SPACE/spaceReadState',
            updateMask='lastReadTime',
            body={'lastReadTime': f'{datetime.datetime(2000, 1, 3).isoformat()}Z'}
    
          ).execute()
    
        # Prints the API's response.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在程式碼中,替換以下內容:

    • SPACE:聊天室名稱,您可以透過 Chat API 的 spaces.list 方法或聊天室網址取得。
  4. 在工作目錄中,建構並執行範例:

    python3 chat_spaceReadState_update.py
    

Node.js

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

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Authenticates with Chat API via user credentials,
    * then updates the space read state for the calling user.
    * @return {!Promise<!Object>}
    */
    async function updateSpaceReadState() {
    
      /**
      * Authenticate with Google Workspace
      * and get user authorization.
      */
      const scopes = [
        'https://www.googleapis.com/auth/chat.users.readstate',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      /**
      * Build a service endpoint for Chat API.
      */
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      /**
      * Use the service endpoint to call Chat API.
      */
      return await chatClient.users.spaces.updateSpaceReadState({
    
        /**
        * The space read state to update.
        *
        * Replace USER with the calling user's ID, Workspace email,
        * or the alias me.
        *
        * Replace SPACE with a space name.
        * Obtain the space name from the spaces resource of Chat API,
        * or from a space's URL.
        */
        name: 'users/me/spaces/SPACE/spaceReadState',
        updateMask: 'lastReadTime',
        requestBody: {
          lastReadTime: '{datetime.datetime(2000, 1, 3).isoformat()}Z'
        }
      });
    }
    
    /**
    * Use the service endpoint to call Chat API.
    */
    getSpaceReadState().then(console.log);
    
  3. 在程式碼中,替換以下內容:

    • SPACE:聊天室名稱,您可以透過 Chat API 的 spaces.list 方法或聊天室網址取得。
  4. 在工作目錄中,建構並執行範例:

    node chat_spaceReadState_update.js
    

Apps Script

本範例使用進階 Chat 服務呼叫 Chat API。

  1. chat.users.readstate 授權範圍新增至 Apps Script 專案的 appsscript.json 檔案:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.users.readstate"
    ]
    
  2. 將以下函式新增至 Apps Script 專案的程式碼:

    /**
    * Authenticates with Chat API via user credentials,
    * then updates the space read state for the calling user.
    * @param {string} spaceReadStateName The resource name of the space read state.
    */
    function updateSpaceReadState(spaceReadStateName) {
      try {
        const time = new Date('January 1, 2000')).toJSON();
        const body = {'lastReadTime': time};
        Chat.Users.Spaces.updateSpaceReadState(spaceReadStateName, body);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log('Failed to update read state with error %s', err.message);
      }
    }
    

Google Chat API 會更新指定空間的讀取狀態,並傳回 SpaceReadState 資源的執行個體。