获取有关用户或 Google Chat 应用的成员资格的详细信息

本指南介绍了如何对 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 实例,详细说明指定的成员资格。