取得使用者詳細資料或 Google Chat 應用程式成員資格#39

本指南說明如何在 Google Chat API 的 membership 資源上使用 get 方法,取得聊天室中使用者或 Chat 應用程式成員資格的詳細資料。

Membership 資源代表使用者或 Google Chat 應用程式是否收到聊天室的邀請、部分或缺席。

透過應用程式驗證進行驗證,可讓 Chat 應用程式在 Google 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 應用程式成員資格的詳細資料

如要取得 Google Chat 中的會員資格詳細資料,請在要求中傳遞以下內容:

  • 透過應用程式驗證,請指定 chat.bot 授權範圍。透過使用者驗證,請指定 chat.memberships.readonlychat.memberships 授權範圍。最佳做法是選擇最嚴格的範圍,確保應用程式仍可正常運作。
  • 呼叫 membership 資源上的 get 方法
  • 通過會員的 name,即可獲得福利。從 Google Chat 成員資源取得會員名稱。

以下透過使用者驗證取得成員資格:

Python

  1. 在工作目錄中,建立名為 chat_membership_get.py 的檔案。
  2. chat_membership_get.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.memberships.readonly"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then gets details about a specified membership.
        '''
    
        # 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().members().get(
    
            # The membership to get.
            #
            # Replace SPACE with a space name.
            # Obtain the space name from the spaces resource of Chat API,
            # or from a space's URL.
            #
            # Replace MEMBER with a membership name.
            # Obtain the membership name from the memberships resource of
            # Chat API.
            name='spaces/SPACE/members/MEMBER'
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在程式碼中,替換以下內容:

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

    python3 chat_membership_get.py
    

Chat API 會傳回 membership 的執行個體,詳細說明指定成員資格。