邀请用户或 Google Chat 应用加入聊天室

本指南介绍如何在 Google Chat API 的 membership 资源中使用 create 方法,以向聊天室(也称为“创建成员”)邀请或添加用户或 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 授权范围。
  • membership 资源调用 create 方法
  • parent 设置为要在其中创建成员的聊天室的资源名称。
  • member 设置为 users/{user},其中 {user} 是要为其创建成员资格的人员,并且是:
    • People API 中 person 的 ID。例如,如果 People API person resourceNamepeople/123456789,则将 membership.member.name 设置为 users/123456789
    • Directory API 中用户的 ID。
    • 用户的电子邮件地址。例如,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:聊天室名称,可通过 Chat API 中的 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.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/USER', type: 'HUMAN'}}
      });
    }
    
    addUserToSpace().then(console.log);
    
  3. 在代码中,替换以下内容:

    • SPACE:聊天室名称,可通过 Chat API 中的 spaces.list 方法或聊天室网址获取。

    • USER:用户 ID。

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

    node add-user-to-space.js
    

Chat API 会返回 membership 的实例,其中详细说明了已创建的成员资格。

向聊天室添加 Chat 应用

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

  • 指定 chat.memberships.app 授权范围。
  • membership 资源调用 create 方法
  • 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 替换为聊天室名称,您可以通过 Chat API 中的 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 替换为聊天室名称,您可以通过 Chat API 中的 spaces.list 方法或聊天室网址获取该名称。

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

    node add-app-to-space.js
    

Chat API 会返回 membership 的实例,其中详细说明了已创建的成员资格。