邀请用户、Google 网上论坛群组或 Google Chat 应用,或将用户添加到聊天室

本指南介绍了如何对 membership 资源使用 create 方法 来邀请或添加用户、Google 群组或 将 Chat 应用添加到聊天室,也称作创建 会员资格。创建成员资格时,如果指定成员的 关闭自动接受政策,则受邀者会收到邀请,且必须接受聊天室 然后再加入。否则,创建成员资格会将该成员 直接上传到指定的空间

通过 Membership 资源 表示是否会邀请真人用户或 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.membershipschat.memberships.app 授权范围。

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.membershipschat.memberships.app 授权范围。

邀请用户或将用户添加到聊天室

如需邀请聊天室或将用户添加到聊天室,请将以下内容传入您的 请求:

  • 指定 chat.memberships 授权范围。
  • 调用 create 方法membership 资源
  • parent 设置为要在其中创建成员资格的聊天室的资源名称。
  • member 设置为 users/{user},其中 {user} 是您要邀请的人 为以下任一项创建成员资格:
    • 。例如,如果 People API resourceNamepeople/123456789,然后设为 membership.member.name 发送至 users/123456789
    • 用户 目录 API。
    • 用户的电子邮件地址。例如 users/222larabrown@gmail.comusers/larabrown@cymbalgroup.com。如果用户使用的是 Google 账号或 属于其他 Google Workspace 组织,您必须使用其 电子邮件地址。

以下示例展示了如何将用户添加到聊天室:

Python

  1. 在您的工作目录中,创建一个名为 chat_membership_user_create.py
  2. chat_membership_user_create.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"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then adds a user to a Chat space by creating a 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().create(
    
            # The space in which to create a membership.
            parent = 'spaces/SPACE',
    
            # Specify which user the membership is for.
            body = {
              'member': {
                'name':'users/USER',
                'type': 'HUMAN'
              }
            }
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在代码中进行以下替换:

    • SPACE:聊天室名称。 您可以从 spaces.list 方法 或通过聊天室网址发送。

    • USER:用户 ID。

  4. 在您的工作目录中,构建并运行该示例:

    python3 chat_membership_user_create.py
    

Node.js

  1. 在您的工作目录中,创建一个名为 add-user-to-space.js 的文件。
  2. add-user-to-space.js 中添加以下代码:

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Adds the user to the Chat space.
    * @return {!Promise<!Object>}
    */
    async function addUserToSpace() {
      const scopes = [
        'https://www.googleapis.com/auth/chat.memberships',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      return await chatClient.spaces.members.create({
        parent: 'spaces/SPACE',
        requestBody: {member: {name: 'users/USER', type: 'HUMAN'}}
      });
    }
    
    addUserToSpace().then(console.log);
    
  3. 在代码中进行以下替换:

    • SPACE:聊天室名称,您可以从 spaces.list 方法 或通过聊天室网址发送。

    • USER:用户 ID。

  4. 在您的工作目录中,运行该示例:

    node add-user-to-space.js
    

Chat API 会返回 membership 详细说明已创建的用户成员资格

邀请 Google 群组或将群组添加到聊天室

如需邀请 Google 群组或向聊天室添加 Google 群组,请将以下内容传入您的 请求:

  • 指定 chat.memberships 授权范围。
  • 调用 create 方法membership 资源
  • parent 设置为要在其中创建成员资格的聊天室的资源名称。
  • groupMember 设置为 groups/{group},其中 {group} 是您要创建的群组 ID 想要为其创建成员资格可以使用 Cloud Identity API。 例如,如果 Cloud Identity API 返回名为 groups/123456789 的组,然后设置 从membership.groupMember.name改为groups/123456789

无法将 Google 群组添加到群聊或私信中,只能添加到 命名空间。以下示例展示了如何将群组添加到命名的聊天室:

Python

  1. 在您的工作目录中,创建一个名为 chat_membership_group_create.py
  2. chat_membership_group_create.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"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then adds a group to a Chat space by creating a 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().create(
    
            # The named space in which to create a membership.
            parent = 'spaces/SPACE',
    
            # Specify which group the membership is for.
            body = {
              'groupMember': {
                'name':'groups/GROUP',
              }
            }
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在代码中进行以下替换:

    • SPACE:聊天室名称。 您可以从 spaces.list 方法 或通过聊天室网址发送。

    • GROUP:群组 ID。

  4. 在您的工作目录中,构建并运行该示例:

    python3 chat_membership_group_create.py
    

Node.js

  1. 在您的工作目录中,创建一个名为 add-group-to-space.js 的文件。
  2. add-group-to-space.js 中添加以下代码:

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Adds the group to the Chat space.
    * @return {!Promise<!Object>}
    */
    async function addUserToSpace() {
      const scopes = [
        'https://www.googleapis.com/auth/chat.memberships',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      return await chatClient.spaces.members.create({
        parent: 'spaces/SPACE',
        requestBody: {groupMember: {name: 'groups/GROUP'}}
      });
    }
    
    addUserToSpace().then(console.log);
    
  3. 在代码中进行以下替换:

    • SPACE:聊天室名称,您可以从 spaces.list 方法 或通过聊天室网址发送。

    • GROUP:群组 ID。

  4. 在您的工作目录中,运行该示例:

    node add-group-to-space.js
    

Chat API 会返回 membership 详细说明已创建的群组成员资格。

将 Chat 扩展应用添加到聊天室

Chat 应用无法将其他应用添加为 空间。将 Chat 扩展应用添加到聊天室 或两个真人用户之间的私信,请在请求中传递以下内容:

  • 指定 chat.memberships.app 授权范围。
  • 调用 create 方法 针对 membership 资源
  • parent 设置为要在其中创建成员资格的聊天室的资源名称。
  • member 设置为 users/app;代表调用 Chat API。

以下示例展示了如何将 Chat 应用添加到聊天室:

Python

  1. 在您的工作目录中,创建一个名为 chat_membership_app_create.py
  2. chat_membership_app_create.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.app"]
    
    def main():
        '''
        Authenticates with Chat API via user credentials,
        then adds the Chat app to a Chat 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().members().create(
    
            # The space in which to create a membership.
            parent = 'spaces/SPACE',
    
            # Set the Chat app as the entity that gets added to the space.
            # 'app' is an alias for the Chat app calling the API.
            body = {
                'member': {
                  'name':'users/app',
                  'type': 'BOT'
                }
            }
    
        ).execute()
    
        # Prints details about the created membership.
        print(result)
    
    if __name__ == '__main__':
        main()
    
  3. 在代码中,将 SPACE 替换为聊天室名称, 您可以从 spaces.list 方法 或通过聊天室网址发送。

  4. 在您的工作目录中,构建并运行该示例:

    python3 chat_membership_app_create.py
    

Node.js

  1. 在您的工作目录中,创建一个名为 add-app-to-space.js 的文件。
  2. add-app-to-space.js 中添加以下代码:

    const chat = require('@googleapis/chat');
    const {authenticate} = require('@google-cloud/local-auth');
    
    /**
    * Adds the app to the Chat space.
    * @return {!Promise<!Object>}
    */
    async function addAppToSpace() {
      const scopes = [
        'https://www.googleapis.com/auth/chat.memberships.app',
      ];
    
      const authClient =
          await authenticate({scopes, keyfilePath: 'client_secrets.json'});
    
      const chatClient = await chat.chat({version: 'v1', auth: authClient});
    
      return await chatClient.spaces.members.create({
        parent: 'spaces/SPACE',
        requestBody: {member: {name: 'users/app', type: 'BOT'}}
      });
    }
    
    addAppToSpace().then(console.log);
    
  3. 在代码中,将 SPACE 替换为聊天室名称, 您可以从 spaces.list 方法 或通过聊天室网址发送。

  4. 在您的工作目录中,运行该示例:

    node add-app-to-space.js
    

Chat API 会返回 membership 详细说明已创建的应用成员资格。