Расширенный чат

Управляйте чатами, участниками и сообщениями.

Сервис Advanced Chat позволяет использовать API Google Chat в Google Apps Script. Этот API позволяет скриптам находить, создавать и изменять чат-пространства, добавлять или удалять участников из этих пространств, а также читать или публиковать сообщения с текстом, карточками, вложениями и реакциями.

Предварительные требования

Это расширенная услуга, которую необходимо включить перед использованием .

Ссылка

Для получения дополнительной информации об этой услуге см. справочную документацию по API чата . Как и все расширенные службы в Apps Script, служба чата использует те же объекты, методы и параметры, что и публичный API.

Пример кода

В этих примерах показано, как выполнять стандартные действия API Google Chat с помощью расширенного сервиса.

Отправьте сообщение с учетными данными пользователя.

В следующем примере показано, как отправить сообщение в чат от имени пользователя.

  1. Добавьте область авторизации chat.messages.create в файл appsscript.json проекта Apps Script:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.messages.create"
    ]
    
  2. Добавьте в код проекта Apps Script функцию, подобную этой:

    /**
     * Posts a new message to the specified space on behalf of the user.
     * @param {string} spaceName The resource name of the space.
     */
    function postMessageWithUserCredentials(spaceName) {
      try {
        const message = { text: "Hello world!" };
        Chat.Spaces.Messages.create(message, spaceName);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log("Failed to create message with error %s", err.message);
      }
    }

Отправьте сообщение с учетными данными приложения.

В следующем примере показано, как отправить сообщение в пространство чата от имени приложения. Использование расширенной службы чата с учетной записью службы не требует указания областей авторизации в файле appsscript.json . Подробную информацию об аутентификации с помощью учетных записей служб см. в разделе «Аутентификация в качестве приложения Google Chat» .

/**
 * Posts a new message to the specified space on behalf of the app.
 * @param {string} spaceName The resource name of the space.
 */
function postMessageWithAppCredentials(spaceName) {
  try {
    // See https://developers.google.com/chat/api/guides/auth/service-accounts
    // for details on how to obtain a service account OAuth token.
    const appToken = getToken_();
    const message = { text: "Hello world!" };
    Chat.Spaces.Messages.create(
      message,
      spaceName,
      {},
      // Authenticate with the service account token.
      { Authorization: `Bearer ${appToken}` },
    );
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log("Failed to create message with error %s", err.message);
  }
}

Найдите место

Следующий пример демонстрирует, как получить информацию о пространстве чата.

  1. Добавьте область авторизации chat.spaces.readonly в файл appsscript.json проекта Apps Script:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.spaces.readonly"
    ]
    
  2. Добавьте в код проекта Apps Script функцию, подобную этой:

    /**
     * Gets information about a Chat space.
     * @param {string} spaceName The resource name of the space.
     */
    function getSpace(spaceName) {
      try {
        const space = Chat.Spaces.get(spaceName);
        console.log("Space display name: %s", space.displayName);
        console.log("Space type: %s", space.spaceType);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log("Failed to get space with error %s", err.message);
      }
    }

Создайте пространство

В следующем примере показано, как создать пространство для чата.

  1. Добавьте область авторизации chat.spaces.create в файл appsscript.json проекта Apps Script:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.spaces.create"
    ]
    
  2. Добавьте в код проекта Apps Script функцию, подобную этой:

    /**
     * Creates a new Chat space.
     */
    function createSpace() {
      try {
        const space = { displayName: "New Space", spaceType: "SPACE" };
        Chat.Spaces.create(space);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log("Failed to create space with error %s", err.message);
      }
    }

Список участников

Следующий пример демонстрирует, как вывести список всех участников чата.

  1. Добавьте область авторизации chat.memberships.readonly в файл appsscript.json проекта Apps Script:

    "oauthScopes": [
      "https://www.googleapis.com/auth/chat.memberships.readonly"
    ]
    
  2. Добавьте в код проекта Apps Script функцию, подобную этой:

    /**
     * Lists all the members of a Chat space.
     * @param {string} spaceName The resource name of the space.
     */
    function listMemberships(spaceName) {
      let response;
      let pageToken = null;
      try {
        do {
          response = Chat.Spaces.Members.list(spaceName, {
            pageSize: 10,
            pageToken: pageToken,
          });
          if (!response.memberships || response.memberships.length === 0) {
            pageToken = response.nextPageToken;
            continue;
          }
          for (const membership of response.memberships) {
            console.log(
              "Member: %s, Role: %s",
              membership.member.displayName,
              membership.role,
            );
          }
          pageToken = response.nextPageToken;
        } while (pageToken);
      } catch (err) {
        // TODO (developer) - Handle exception
        console.log("Failed with error %s", err.message);
      }
    }

Устранение неполадок

If you encounter Error 400: invalid_scope with the error message Some requested scopes cannot be shown , it means you haven't specified any authorization scopes in the Apps Script project's appsscript.json file. In most cases, Apps Script automatically determines what scopes a script needs, but when you use the Chat advanced service, you must manually add the authorization scopes that your script uses to your Apps Script project's manifest file. See Setting explicit scopes .

Для устранения ошибки добавьте соответствующие области авторизации в файл appsscript.json проекта Apps Script в составе массива oauthScopes . Например, для вызова метода spaces.messages.create добавьте следующее:

"oauthScopes": [
  "https://www.googleapis.com/auth/chat.messages.create"
]

Ограничения и соображения

Сервис расширенного чата не поддерживает:

Для загрузки вложенного сообщения или вызова метода из предварительной версии для разработчиков используйте вместо этого UrlFetchApp .