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

Служба расширенных событий Google Workspace позволяет использовать API событий Google Workspace в скриптах приложений. Этот API позволяет вам подписаться на ресурсы Google Workspace, чтобы получать соответствующие события, которые вас интересуют. События представляют собой изменения в ресурсах, например, когда ресурсы создаются, обновляются или удаляются.

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

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

    "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:

продвинутый/events.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:

продвинутый/events.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 следующую функцию:

продвинутый/events.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:

продвинутый/events.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 следующую функцию:

продвинутый/events.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 следующую функцию:

продвинутый/events.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 Events возвращают длительную операцию . Чтобы определить статус операции, вы можете использовать метод operations.get() .

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

продвинутый/events.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 Events, например subscriptions.create() или subscriptions.patch() .