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

本指南介绍了如何对 Google Chat API 的 Membership 资源使用 create() 方法,将用户、Google 群组或 Chat 应用邀请或添加到聊天室(也称为创建成员资格)。创建会员资格时,如果指定会员已关闭自动接受政策,那么在收到邀请后,他们必须先接受聊天室邀请,然后才能加入。否则,创建会员资格会直接将成员添加到指定聊天室。

如果您是 Google Workspace 管理员,则可以将用户、Google 群组或 Chat 应用添加到 Google Workspace 组织中的任何聊天室。

Membership 资源表示有人为用户或 Google Chat 应用发出了加入聊天室的邀请、用户或 Google Chat 应用已加入聊天室,还是未加入聊天室。

前提条件

Node.js

Python

Java

Apps 脚本

邀请用户加入聊天室或将用户添加为聊天室用户

如需邀请或将用户添加到启用了用户身份验证的聊天室,请在请求中传递以下内容:

  • 指定 chat.memberships 授权范围。
  • 调用 CreateMembership() 方法。
  • parent 作为要创建成员资格的聊天室的资源名称传递。
  • membership 作为 Membership 的实例传递,并使用以下代码设置其字段 member
    • 设置为 HUMANtype 字段。
    • name 字段设置为 users/{user},其中 {user} 是您要添加到聊天室的用户。如需指定 Chat 用户,请将 {user} 替换为以下任一项:
      • People API 中的人员的 ID。例如,如果 People API person resourceNamepeople/123456789,则使用值 users/123456789
      • Directory API 中的用户 ID。
      • 用户的电子邮件地址。例如 users/222larabrown@gmail.comusers/larabrown@cymbalgroup.com。如果用户使用的是 Google 账号或属于其他 Google Workspace 组织,您必须使用其电子邮件地址。

以下示例通过用户身份验证将用户添加到聊天室:

Node.js

chat/client-libraries/cloud/create-membership-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships'];

// This sample shows how to create membership with user credential for a human user
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    membership: {
      member: {
        // Replace USER_NAME here
        name: 'users/USER_NAME',
        // User type for the membership
        type: 'HUMAN'
      }
    }
  };

  // Make the request
  const response = await chatClient.createMembership(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_membership_user_cred.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.memberships"]

# This sample shows how to create membership with user credential for a human
# user
def create_membership_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMembershipRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        membership = {
            "member": {
                # Replace USER_NAME here
                "name": "users/USER_NAME",
                # user type for the membership
                "type_": "HUMAN"
            }
        }
    )

    # Make the request
    response = client.create_membership(request)

    # Handle the response
    print(response)

create_membership_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMembershipRequest;
import com.google.chat.v1.Membership;
import com.google.chat.v1.SpaceName;
import com.google.chat.v1.User;

// This sample shows how to create membership with user credential for a human
// user.
public class CreateMembershipUserCred {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.memberships";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMembershipRequest.Builder request = CreateMembershipRequest.newBuilder()
        // replace SPACE_NAME here
        .setParent("spaces/SPACE_NAME")
        .setMembership(Membership.newBuilder()
          .setMember(User.newBuilder()
            // replace USER_NAME here
            .setName("users/USER_NAME")
            // user type for the membership
            .setType(User.Type.HUMAN)));
      Membership response = chatServiceClient.createMembership(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps 脚本

chat/advanced-service/Main.gs
/**
 * This sample shows how to create membership with user credential for a human user
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.memberships'
 * referenced in the manifest file (appsscript.json).
 */
function createMembershipUserCred() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  const membership = {
    member: {
      // TODO(developer): Replace USER_NAME here
      name: 'users/USER_NAME',
      // User type for the membership
      type: 'HUMAN'
    }
  };

  // Make the request
  const response = Chat.Spaces.Members.create(membership, parent);

  // Handle the response
  console.log(response);
}

如需运行该示例,请替换以下内容:

  • SPACE_NAME:聊天室的 name 中的 ID。您可以通过调用 ListSpaces() 方法或从聊天室的网址中获取此 ID。
  • USER_NAME:用户 ID。

Chat API 会返回一个 Membership 实例,其中详细说明了创建的用户成员资格。

向聊天室邀请或添加 Google 群组

如需使用用户身份验证将 Google 群组邀请或添加到聊天室(应用身份验证不支持将 Google 群组邀请或添加到聊天室),请在请求中传递以下内容:

  • 指定 chat.memberships 授权范围。
  • 调用 CreateMembership() 方法。
  • parent 作为要创建成员资格的聊天室的资源名称传递。
  • membership 作为 Membership 的实例传递,并将 groupMembername 字段设置为 groups/{group},其中 {group} 是您要为其创建成员资格的群组 ID。您可以使用 Cloud Identity API 检索群组的 ID。

您无法将 Google 群组中的群组添加到群聊或私信中,只能添加到命名聊天室中。

以下示例将群组添加到需要用户身份验证的命名聊天室:

Node.js

chat/client-libraries/cloud/create-membership-user-cred-for-group.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships'];

// This sample shows how to create membership with user credential for a group
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    membership: {
      groupMember: {
        // Replace GROUP_NAME here
        name: 'groups/GROUP_NAME'
      }
    }
  };

  // Make the request
  const response = await chatClient.createMembership(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_membership_user_cred_for_group.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.memberships"]

# This sample shows how to create membership with user credential for a group
def create_membership_with_user_cred_for_group():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMembershipRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        membership = {
            "groupMember": {
                # Replace GROUP_NAME here
                "name": "groups/GROUP_NAME"
            }
        }
    )

    # Make the request
    response = client.create_membership(request)

    # Handle the response
    print(response)

create_membership_with_user_cred_for_group()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForGroup.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMembershipRequest;
import com.google.chat.v1.Membership;
import com.google.chat.v1.SpaceName;
import com.google.chat.v1.Group;

// This sample shows how to create membership with user credential for a group.
public class CreateMembershipUserCredForGroup {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.memberships";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMembershipRequest.Builder request = CreateMembershipRequest.newBuilder()
        // replace SPACE_NAME here
        .setParent("spaces/SPACE_NAME")
        .setMembership(Membership.newBuilder()
          .setGroupMember(Group.newBuilder()
            // replace GROUP_NAME here
            .setName("groups/GROUP_NAME")));
      Membership response = chatServiceClient.createMembership(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps 脚本

chat/advanced-service/Main.gs
/**
 * This sample shows how to create membership with user credential for a group
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.memberships'
 * referenced in the manifest file (appsscript.json).
 */
function createMembershipUserCredForGroup() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  const membership = {
    groupMember: {
      // TODO(developer): Replace GROUP_NAME here
      name: 'groups/GROUP_NAME'
    }
  };

  // Make the request
  const response = Chat.Spaces.Members.create(membership, parent);

  // Handle the response
  console.log(response);
}

如需运行该示例,请替换以下内容:

  • SPACE_NAME:聊天室的 name 中的 ID。您可以通过调用 ListSpaces() 方法或从聊天室的网址中获取此 ID。
  • GROUP_NAME:组 ID。

Chat API 会返回一个 Membership 实例,其中详细说明了创建的用户成员资格。

将 Chat 应用添加到聊天室

Chat 应用无法将其他应用添加为聊天室成员。如需将 Chat 应用添加到聊天室或两位用户之间的私信中,请在请求中使用用户身份验证传递以下内容(应用身份验证不支持邀请或将 Chat 应用添加到聊天室):

  • 指定 chat.memberships.app 授权范围。
  • 调用 CreateMembership() 方法。
  • parent 作为要创建成员资格的聊天室的资源名称传递。
  • membership 作为 Membership 的实例传递,并使用以下代码设置其字段 member
    • 设置为 BOTtype 字段。
    • name 字段设置为 users/app;一个别名,表示调用 Chat API 的应用。

以下示例将 Chat 应用添加到聊天室:

Node.js

chat/client-libraries/cloud/create-membership-user-cred-for-app.js
import {createClientWithUserCredentials} from './authentication-utils.js';

const USER_AUTH_OAUTH_SCOPES = ['https://www.googleapis.com/auth/chat.memberships.app'];

// This sample shows how to create membership with app credential for an app
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(USER_AUTH_OAUTH_SCOPES);

  // Initialize request argument(s)
  const request = {
    // Replace SPACE_NAME here.
    parent: 'spaces/SPACE_NAME',
    membership: {
      member: {
        // Member name for app membership, do not change this
        name: 'users/app',
        // User type for the membership
        type: 'BOT'
      }
    }
  };

  // Make the request
  const response = await chatClient.createMembership(request);

  // Handle the response
  console.log(response);
}

main().catch(console.error);

Python

chat/client-libraries/cloud/create_membership_user_cred_for_app.py
from authentication_utils import create_client_with_user_credentials
from google.apps import chat_v1 as google_chat

SCOPES = ["https://www.googleapis.com/auth/chat.memberships.app"]

# This sample shows how to create membership with app credential for an app
def create_membership_with_user_cred_for_app():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.CreateMembershipRequest(
        # Replace SPACE_NAME here
        parent = "spaces/SPACE_NAME",
        membership = {
            "member": {
                # member name for app membership, do not change this.
                "name": "users/app",
                # user type for the membership
                "type_": "BOT"
            }
        }
    )

    # Make the request
    response = client.create_membership(request)

    # Handle the response
    print(response)

create_membership_with_user_cred_for_app()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/CreateMembershipUserCredForApp.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.CreateMembershipRequest;
import com.google.chat.v1.Membership;
import com.google.chat.v1.SpaceName;
import com.google.chat.v1.User;

// This sample shows how to create membership with user credential for the
// calling app.
public class CreateMembershipUserCredForApp {

  private static final String SCOPE =
    "https://www.googleapis.com/auth/chat.memberships.app";

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      CreateMembershipRequest.Builder request = CreateMembershipRequest.newBuilder()
        // replace SPACE_NAME here
        .setParent("spaces/SPACE_NAME")
        .setMembership(Membership.newBuilder()
          .setMember(User.newBuilder()
            // member name for app membership, do not change this.
            .setName("users/app")
            // user type for the membership
            .setType(User.Type.BOT)));
      Membership response = chatServiceClient.createMembership(request.build());

      System.out.println(JsonFormat.printer().print(response));
    }
  }
}

Apps 脚本

chat/advanced-service/Main.gs
/**
 * This sample shows how to create membership with app credential for an app
 * 
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.memberships.app'
 * referenced in the manifest file (appsscript.json).
 */
function createMembershipUserCredForApp() {
  // Initialize request argument(s)
  // TODO(developer): Replace SPACE_NAME here.
  const parent = 'spaces/SPACE_NAME';
  const membership = {
    member: {
      // Member name for app membership, do not change this
      name: 'users/app',
      // User type for the membership
      type: 'BOT'
    }
  };

  // Make the request
  const response = Chat.Spaces.Members.create(membership, parent);

  // Handle the response
  console.log(response);
}

如需运行示例,请将 SPACE_NAME 替换为聊天室的 name 中的 ID。您可以通过调用 ListSpaces() 方法或从聊天室的网址中获取此 ID。

Chat API 会返回一个 Membership 实例,其中详细说明了创建的用户成员资格。

将用户作为 Chat 应用邀请或添加到聊天室

应用身份验证需要一次性管理员批准

如需使用应用身份验证功能邀请或添加用户加入聊天室,请在请求中传递以下内容:

  • 指定 chat.app.memberships 授权范围。
  • membership 资源调用 create 方法
  • parent 设置为要创建成员资格的聊天室的资源名称。
  • member 设置为 users/{user},其中 {user} 是您要为其创建会员资格的用户,并且符合以下条件之一:
    • People API 中的人员的 ID。例如,如果 People API person resourceNamepeople/123456789,请将 membership.member.name 设置为 users/123456789
    • Directory API 中的用户 ID。
    • 用户的电子邮件地址。例如 users/222larabrown@gmail.comusers/larabrown@cymbalgroup.com。如果用户使用的是 Google 账号或属于其他 Google Workspace 组织,您必须使用其电子邮件地址。

创建 API 密钥

如需调用开发者预览版 API 方法,您必须使用 API 发现文档的非公开开发者预览版。如需对请求进行身份验证,您必须传递 API 密钥。

如需创建 API 密钥,请打开应用的 Google Cloud 项目,然后执行以下操作:

  1. 在 Google Cloud 控制台中,依次点击“菜单”图标 > API 和服务 > 凭据

    进入“凭据”页面

  2. 依次点击创建凭据 > API 密钥
  3. 系统会显示您的新 API 密钥。
    • 点击“复制”图标 以复制您的 API 密钥,以便在应用的代码中使用。您也可以在项目凭据的“API 密钥”部分找到该 API 密钥。
    • 点击限制密钥可更新高级设置并限制 API 密钥的使用。如需了解详情,请参阅应用 API 密钥限制

编写用于调用 Chat API 的脚本

以下示例使用应用身份验证将用户添加到聊天室:

Python

  1. 在工作目录中,创建一个名为 chat_membership_app_create.py 的文件。
  2. chat_membership_app_create.py 中添加以下代码:

    from google.oauth2 import service_account
    from apiclient.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.app.memberships"]
    
    def main():
        '''
        Authenticates with Chat API using app authentication,
        then adds a user to a Chat space by creating a membership.
        '''
    
        # Specify service account details.
        creds = (
            service_account.Credentials.from_service_account_file('credentials.json')
            .with_scopes(SCOPES)
        )
    
        # Build a service endpoint for Chat API.
        chat = build('chat', 'v1', credentials=creds, discoveryServiceUrl='https://chat.googleapis.com/$discovery/rest?version=v1&labels=DEVELOPER_PREVIEW&key=API_KEY')
    
        # 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. 在代码中,替换以下内容:

    • API_KEY:您创建的用于构建 Chat API 服务端点的 API 密钥。

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

    • USER:用户 ID。

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

    python3 chat_membership_app_create.py

以 Google Workspace 管理员身份向聊天室添加用户或 Google 群组

如果您是 Google Workspace 管理员,则可以调用 create() 方法,将用户、Google 群组或 Chat 应用添加到 Google Workspace 组织中的任何聊天室。

如需以 Google Workspace 管理员身份调用此方法,请执行以下操作:

  • 使用用户身份验证调用该方法,并指定支持使用管理员权限调用该方法的授权范围
  • 在请求中,将查询参数 useAdminAccess 指定为 true

如需了解详情和示例,请参阅以 Google Workspace 管理员身份管理 Google Chat 聊天室

限制和注意事项

  • 使用应用身份验证时,Chat 应用可以邀请或添加用户,但 Google 群组或 Chat 应用无法执行此操作。如需自行添加,Chat 应用必须使用 chat.memberships 授权范围的用户身份验证