创建 Google Chat 聊天室并添加成员

本指南介绍了如何使用 setUp() 方法在 Google Chat API 的 Space 资源上创建 Chat 聊天室,并向其中添加成员。

`Space` Space 资源 表示用户和 Chat 应用可以发送消息、 共享文件和协作的场所。聊天室有多种类型:

  • 私信 (DM) 是两位用户之间或用户与 Chat 应用之间的对话。
  • 群聊是三位或更多用户与 Chat 应用之间的对话。
  • 已命名的聊天室是用户发送消息、共享文件和协作的永久场所。

您可以使用 setUp() 方法执行以下任一操作:

  • 创建具有初始成员的已命名聊天室。
  • 在两人之间创建私信 (DM)。
  • 在多人之间设置群组消息。

设置聊天室时,请注意以下事项:

  • 调用(经过身份验证的)用户会自动添加到聊天室,因此您无需在请求中指定用户的成员资格。
  • 创建私信 (DM) 时,如果两个用户之间存在 DM,则系统会返回该 DM。否则,系统会创建 DM。
  • 创建群聊时,如果请求中提供的任何成员资格都未成功添加到群聊(例如,权限问题),则可能会创建一个空群聊(仅包含调用用户)。
  • 您无法设置包含消息串式回复的聊天室,也无法添加 Google Workspace 组织外部的用户。
  • 系统会过滤掉请求中提供的重复成员资格(包括调用用户),而不会导致请求错误。
  • 当 Google Workspace 管理员 为其整个 Google Workspace 组织安装 Chat 应用时, Google Chat 会在已安装的 Chat 应用与组织中的每个用户之间创建 DM,因此 无需以编程方式设置 DM。您可以 列出聊天室以返回所有 DM,也可以 查找私信 以获取有关特定 DM 的详细信息。

前提条件

Node.js

Python

Java

Apps 脚本

设置聊天室

如需设置聊天室,请在请求中传递以下内容:

  • 指定 chat.spaces.createchat.spaces 授权范围。
  • 调用 SetUpSpace() 方法。
  • space 作为 Space 的实例传递,其中包含所有必需的字段,例如 displayNamespaceType
  • memberships 作为 Membership 实例的数组传递。对于每个实例:
    • 指定 users/{user} 以将人工用户添加为聊天室成员,其中 {user} 是 People API 中 person{person_id},或者是 Directory API 中 user 的 ID。例如,如果 People API 人员 resourceNamepeople/123456789,您可以通过添加一个成员资格(其中 member.nameusers/123456789)将该用户添加到聊天室。
    • 指定 groups/{group} 以将群组添加为聊天室成员,其中 {group} 是您要为其创建成员资格的群组 ID。您可以使用Cloud Identity API检索群组的 ID。例如,如果 Cloud Identity API 返回一个名称为 groups/123456789 的群组,则将 membership.groupMember.name 设置为 groups/123456789。Google 网上论坛中的群组无法添加到群聊或 DM,只能添加到已命名的聊天室。

如需在调用用户与另一个人用户之间创建 DM,请在请求中指定该人用户的成员资格。

如需在调用用户与调用应用之间创建私信,请将 space.singleUserBotDm 设置为 true,并且不指定任何成员资格。您只能使用此方法与通话应用设置私信。如需将通话应用添加为聊天室的成员,或添加到两个人用户之间现有的私信,请参阅创建成员资格

以下示例创建了一个已命名的聊天室,并为两个人工用户(经过身份验证的用户和另一个用户)创建了一个聊天室成员资格。

Node.js

chat/client-libraries/cloud/set-up-space-user-cred.js
import {createClientWithUserCredentials} from './authentication-utils.js';

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

// This sample shows how to set up a named space with one initial member
// with user credential
async function main() {
  // Create a client
  const chatClient = await createClientWithUserCredentials(
    USER_AUTH_OAUTH_SCOPES,
  );

  // Initialize request argument(s)
  const request = {
    space: {
      spaceType: 'SPACE',
      // Replace DISPLAY_NAME here.
      displayName: 'DISPLAY_NAME',
    },
    memberships: [
      {
        member: {
          // Replace USER_NAME here.
          name: 'users/USER_NAME',
          type: 'HUMAN',
        },
      },
    ],
  };

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

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

await main();

Python

chat/client-libraries/cloud/set_up_space_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.spaces.create"]

def set_up_space_with_user_cred():
    # Create a client
    client = create_client_with_user_credentials(SCOPES)

    # Initialize request argument(s)
    request = google_chat.SetUpSpaceRequest(
        space = {
            "space_type": 'SPACE',
            # Replace DISPLAY_NAME here.
            "display_name": 'DISPLAY_NAME'
        },
        memberships = [{
            "member": {
                # Replace USER_NAME here.
                "name": 'users/USER_NAME',
                "type_": 'HUMAN'
            }
        }]
    )

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

    # Handle the response
    print(response)

set_up_space_with_user_cred()

Java

chat/client-libraries/cloud/src/main/java/com/google/workspace/api/chat/samples/SetUpSpaceUserCred.java
import com.google.chat.v1.ChatServiceClient;
import com.google.chat.v1.Membership;
import com.google.chat.v1.SetUpSpaceRequest;
import com.google.chat.v1.Space;
import com.google.chat.v1.User;

// This sample shows how to set up a named space with one initial member with
// user credential.
public class SetUpSpaceUserCred {

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

  public static void main(String[] args) throws Exception {
    try (ChatServiceClient chatServiceClient =
        AuthenticationUtils.createClientWithUserCredentials(
          ImmutableList.of(SCOPE))) {
      SetUpSpaceRequest.Builder request = SetUpSpaceRequest.newBuilder()
        .setSpace(Space.newBuilder()
          .setSpaceType(Space.SpaceType.SPACE)
          // Replace DISPLAY_NAME here.
          .setDisplayName("DISPLAY_NAME"))
        .addAllMemberships(ImmutableList.of(Membership.newBuilder()
          .setMember(User.newBuilder()
            // Replace USER_NAME here.
            .setName("users/USER_NAME")
            .setType(User.Type.HUMAN)).build()));
      Space response = chatServiceClient.setUpSpace(request.build());

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

Apps 脚本

chat/advanced-service/Main.gs
/**
 * This sample shows how to set up a named space with one initial member with
 * user credential.
 *
 * It relies on the OAuth2 scope 'https://www.googleapis.com/auth/chat.spaces.create'
 * referenced in the manifest file (appsscript.json).
 */
function setUpSpaceUserCred() {
  // Initialize request argument(s)
  const space = {
    spaceType: "SPACE",
    // TODO(developer): Replace DISPLAY_NAME here
    displayName: "DISPLAY_NAME",
  };
  const memberships = [
    {
      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.setup({
    space: space,
    memberships: memberships,
  });

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

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

  • DISPLAY_NAME:新聊天室的显示名称。
  • USER_NAME:要为其添加成员资格的其他用户的 ID。

如需前往聊天室,请使用聊天室的资源 ID 构建聊天室的网址。 您可以从 Google Chat 响应正文中的聊天室 name 获取资源 ID。例如,如果聊天室的 namespaces/1234567,您可以使用以下网址前往该聊天室:https://mail.google.com/chat/u/0/#chat/space/1234567