Servizio avanzato per eventi Google Workspace

Il servizio avanzato Google Workspace Events ti consente di utilizzare l'API Google Workspace Events in Apps Script. Questa API ti consente di iscriverti alle risorse di Google Workspace per ricevere gli eventi pertinenti che ti interessano. Gli eventi rappresentano le modifiche alle risorse, ad esempio quando le risorse vengono create, aggiornate o eliminate.

Prerequisiti

  • Un progetto Apps Script che utilizza un progetto Google Cloud standard anziché quello predefinito creato automaticamente da Apps Script.
  • Un argomento Pub/Sub creato nello stesso progetto Google Cloud per ricevere gli eventi di abbonamento. Per creare un argomento Pub/Sub, consulta Creare un argomento Pub/Sub e sottoscrivere una sottoscrizione.
  • Per abbonarti agli eventi di Chat, devi aver configurato un'app Google Chat nella pagina di configurazione dell'API Chat nella console Google Cloud. Per creare un'app Google Chat, consulta Creare un'app Google Chat con Apps Script.
  • Gli ambiti di autorizzazione necessari aggiunti al file appsscript.json del progetto Apps Script. Gli ambiti necessari dipendono dai tipi di risorse ed eventi di destinazione degli abbonamenti. Per maggiori dettagli, vedi Scegliere gli ambiti dell'API Google Workspace Events. Ad esempio:

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

Riferimento

Per saperne di più su questo servizio, consulta la documentazione di riferimento dell'API Google Workspace Events. Come tutti i servizi avanzati in Apps Script, il servizio Google Workspace Events utilizza gli stessi oggetti, metodi e parametri dell'API pubblica.

Codice di esempio

Questi esempi mostrano come eseguire azioni comuni dell'API Google Workspace Events utilizzando il servizio avanzato.

Creare una sottoscrizione

Per creare un abbonamento a una risorsa Google Workspace, aggiungi la seguente funzione al codice del progetto Apps Script:

advanced/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);
  }
}

Elenco sottoscrizioni

Per elencare gli abbonamenti filtrati in base ai tipi di eventi e alla risorsa di destinazione, aggiungi la seguente funzione al codice del progetto Apps Script:

advanced/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);
  }
}

Recupero sottoscrizione

Per ottenere informazioni su un abbonamento, aggiungi la seguente funzione al codice del progetto Apps Script:

advanced/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);
  }
}

Aggiorna abbonamento

Per aggiornare o rinnovare un abbonamento, aggiungi la seguente funzione al codice del progetto Apps Script:

advanced/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);
  }
}

Riattiva abbonamento

Per riattivare un abbonamento, aggiungi la seguente funzione al codice del progetto Apps Script:

advanced/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);
  }
}

Eliminazione di una sottoscrizione

Per eliminare un abbonamento, aggiungi la seguente funzione al codice del progetto Apps Script:

advanced/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);
  }
}

Recupera operazione

La maggior parte dei metodi dell'API Google Workspace Events restituisce un'operazione a lunga esecuzione. Per determinare lo stato dell'operazione, puoi utilizzare il metodo operations.get().

Per ottenere informazioni su un'operazione, aggiungi la seguente funzione al codice del progetto Apps Script:

advanced/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);
  }
}

Per ottenere il nome di un'operazione, utilizza il valore del campo name restituito da uno dei metodi dell'API Google Workspace Events, ad esempio subscriptions.create() o subscriptions.patch().