Расширенная служба событий Google Workspace

Служба Advanced Google Workspace Events позволяет использовать API Google Workspace Events в Apps Script. Этот API позволяет подписываться на ресурсы Google Workspace, чтобы получать интересующие вас события. События представляют собой изменения ресурсов, например, создание, обновление или удаление ресурсов.

Предпосылки

  • Проект Apps Script, использующий стандартный проект Google Cloud вместо проекта по умолчанию, созданного автоматически Apps Script.
  • Тема Pub/Sub , созданная в том же проекте Google Cloud для получения событий подписки. Чтобы создать тему Pub/Sub, см. раздел Создание темы Pub/Sub и подписка на нее .
  • Чтобы подписаться на события чата, необходимо настроить приложение Google Chat на странице конфигурации Chat API в консоли Google Cloud. Чтобы создать приложение Google Chat, см. статью Создание приложения Google Chat с помощью Apps Script .
  • Необходимые области авторизации, добавленные в файл appsscript.json проекта Apps Script. Необходимые области зависят от типов целевых ресурсов и событий подписок. Подробнее см. в разделе Выбор областей API событий Google Workspace . Например:

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

Ссылка

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

Пример кода

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

Создать подписку

Чтобы создать подписку на ресурс Google Workspace, добавьте следующую функцию в код проекта Apps Script:

расширенные/события.gs
/**
 * Creates a subscription to receive events about a Google Workspace resource.
 * For a list of supported resources and event types, see the
 * [Google Workspace Events API Overview](https://developers.google.com/workspace/events#supported-events).
 * For additional information, see the
 * [subscriptions.create](https://developers.google.com/workspace/events/reference/rest/v1/subscriptions/create)
 * method reference.
 * @param {!string} targetResource The full resource name of the Google Workspace resource to subscribe to.
 * @param {!string|!Array<string>} eventTypes The types of events to receive about the resource.
 * @param {!string} pubsubTopic The resource name of the Pub/Sub topic that receives events from the subscription.
 */
function createSubscription(targetResource, eventTypes, pubsubTopic) {
  try {
    const operation = WorkspaceEvents.Subscriptions.create({
      targetResource: targetResource,
      eventTypes: eventTypes,
      notificationEndpoint: {
        pubsubTopic: pubsubTopic,
      },
    });
    console.log(operation);
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed to create subscription with error %s', err.message);
  }
}

Список подписок

Чтобы вывести список подписок, отсортированных по типам событий и целевому ресурсу, добавьте следующую функцию в код проекта Apps Script:

расширенные/события.gs
/**
 * Lists subscriptions created by the calling app filtered by one or more event types and optionally by a target resource.
 * For additional information, see the
 * [subscriptions.list](https://developers.google.com/workspace/events/reference/rest/v1/subscriptions/list)
 * method reference.
 * @param {!string} filter The query filter.
 */
function listSubscriptions(filter) {
  try {
    const response = WorkspaceEvents.Subscriptions.list({ filter });
    console.log(response);
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed to list subscriptions with error %s', err.message);
  }
}

Оформить подписку

Чтобы получить информацию о подписке, добавьте следующую функцию в код проекта Apps Script:

расширенные/события.gs
/**
 * Gets details about a subscription.
 * For additional information, see the
 * [subscriptions.get](https://developers.google.com/workspace/events/reference/rest/v1/subscriptions/get)
 * method reference.
 * @param {!string} name The resource name of the subscription.
 */
function getSubscription(name) {
  try {
    const subscription = WorkspaceEvents.Subscriptions.get(name);
    console.log(subscription);
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed to get subscription with error %s', err.message);
  }
}

Обновить подписку

Чтобы обновить или продлить подписку, добавьте следующую функцию в код проекта Apps Script:

расширенные/события.gs
/**
 * Updates an existing subscription.
 * This can be used to renew a subscription that is about to expire.
 * For additional information, see the
 * [subscriptions.patch](https://developers.google.com/workspace/events/reference/rest/v1/subscriptions/patch)
 * method reference.
 * @param {!string} name The resource name of the subscription.
 */
function patchSubscription(name) {
  try {
    const operation = WorkspaceEvents.Subscriptions.patch({
      // Setting the TTL to 0 seconds extends the subscription to its maximum expiration time.
      ttl: '0s',
    }, name);
    console.log(operation);
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed to update subscription with error %s', err.message);
  }
}

Повторно активировать подписку

Чтобы повторно активировать подписку, добавьте следующую функцию в код проекта Apps Script:

расширенные/события.gs
/**
 * Reactivates a suspended subscription.
 * Before reactivating, you must resolve any errors with the subscription.
 * For additional information, see the
 * [subscriptions.reactivate](https://developers.google.com/workspace/events/reference/rest/v1/subscriptions/reactivate)
 * method reference.
 * @param {!string} name The resource name of the subscription.
 */
function reactivateSubscription(name) {
  try {
    const operation = WorkspaceEvents.Subscriptions.reactivate({}, name);
    console.log(operation);
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed to reactivate subscription with error %s', err.message);
  }
}

Удалить подписку

Чтобы удалить подписку, добавьте следующую функцию в код проекта Apps Script:

расширенные/события.gs
/**
 * Deletes a subscription.
 * For additional information, see the
 * [subscriptions.delete](https://developers.google.com/workspace/events/reference/rest/v1/subscriptions/delete)
 * method reference.
 * @param {!string} name The resource name of the subscription.
 */
function deleteSubscription(name) {
  try {
    const operation = WorkspaceEvents.Subscriptions.remove(name);
    console.log(operation);
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed to delete subscription with error %s', err.message);
  }
}

Получить операцию

Большинство методов API событий Google Workspace возвращают длительную операцию . Чтобы определить статус операции, можно использовать метод operations.get() .

Чтобы получить информацию об операции, добавьте следующую функцию в код проекта Apps Script:

расширенные/события.gs
/**
 * Gets details about an operation returned by one of the methods on the subscription
 * resource of the Google Workspace Events API.
 * For additional information, see the
 * [operations.get](https://developers.google.com/workspace/events/reference/rest/v1/operations/get)
 * method reference.
 * @param {!string} name The resource name of the operation.
 */
function getOperation(name) {
  try {
    const operation = WorkspaceEvents.Operations.get(name);
    console.log(operation);
  } catch (err) {
    // TODO (developer) - Handle exception
    console.log('Failed to get operation with error %s', err.message);
  }
}

Чтобы получить имя операции, используйте значение из поля name , возвращаемого одним из методов API событий Google Workspace, например subscriptions.create() или subscriptions.patch() .