可安裝的觸發條件 (original) (raw)

可安裝的觸發條件

透過集合功能整理內容 你可以依據偏好儲存及分類內容。

簡易觸發條件一樣,安裝式觸發條件可讓 Apps Script 在發生特定事件 (例如開啟文件) 時自動執行函式。不過,可安裝的觸發事件比起簡單的觸發事件,提供更大的彈性:可安裝的觸發事件可以呼叫需要授權服務,提供多種額外事件類型 (包括時間導向 (時鐘) 觸發事件),且可透過程式設計控制。無論是簡單觸發條件還是可安裝的觸發條件,Apps Script 都會將觸發函式的事件物件傳遞給觸發事件的內容,其中包含事件發生的內容。

限制

雖然可安裝的觸發條件比簡單觸發條件更具彈性,但仍有幾項限制:

時間觸發條件

時間觸發事件 (也稱為時鐘觸發事件) 類似於 Unix 中的 cron 工作。時間觸發事件可讓指令碼在特定時間或定期間隔執行,頻率可從每分鐘到每月一次不等。(請注意,外掛程式最多每小時只能使用一次時間觸發條件)。時間可能會稍微隨機產生。舉例來說,如果您建立上午 9 點的週期性觸發事件,Apps Script 會選擇上午 9 點至 10 點之間的時間,然後每天都維持相同的時間,以便在觸發事件再次觸發前,讓 24 小時過去。

以下是 Google Chat 應用程式的範例,這個應用程式會在每個聊天室中每分鐘張貼訊息:

// Example app for Google Chat that demonstrates app-initiated messages
// by spamming the user every minute.
//
// This app makes use of the Apps Script OAuth2 library at:
//     https://github.com/googlesamples/apps-script-oauth2
//
// Follow the instructions there to add the library to your script.

// When added to a space, we store the space's ID in ScriptProperties.
function onAddToSpace(e) {
  PropertiesService.getScriptProperties()
      .setProperty(e.space.name, '');
  return {
    'text': 'Hi! I\'ll post a message here every minute. ' +
            'Please remove me after testing or I\'ll keep spamming you!'
  };
}

// When removed from a space, we remove the space's ID from ScriptProperties.
function onRemoveFromSpace(e) {
  PropertiesService.getScriptProperties()
      .deleteProperty(e.space.name);
}

// Add a trigger that invokes this function every minute in the
// "Edit > Current Project's Triggers" menu. When it runs, it
// posts in each space the app was added to.
function onTrigger() {
  var spaceIds = PropertiesService.getScriptProperties()
      .getKeys();
  var message = { 'text': 'Hi! It\'s now ' + (new Date()) };
  for (var i = 0; i < spaceIds.length; ++i) {
    postMessage(spaceIds[i], message);
  }
}
var SCOPE = 'https://www.googleapis.com/auth/chat.bot';
// The values below are copied from the JSON file downloaded upon
// service account creation.
// For SERVICE_ACCOUNT_PRIVATE_KEY, remember to include the BEGIN and END lines
// of the private key
var SERVICE_ACCOUNT_PRIVATE_KEY = '...';
var SERVICE_ACCOUNT_EMAIL = 'service-account@project-id.iam.gserviceaccount.com';

// Posts a message into the given space ID via the API, using
// service account authentication.
function postMessage(spaceId, message) {
  var service = OAuth2.createService('chat')
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')
      .setPrivateKey(SERVICE_ACCOUNT_PRIVATE_KEY)
      .setClientId(SERVICE_ACCOUNT_EMAIL)
      .setPropertyStore(PropertiesService.getUserProperties())
      .setScope(SCOPE);
  if (!service.hasAccess()) {
    Logger.log('Authentication error: %s', service.getLastError());
    return;
  }
  var url = 'https://chat.googleapis.com/v1/' + spaceId + '/messages';
  UrlFetchApp.fetch(url, {
    method: 'post',
    headers: { 'Authorization': 'Bearer ' + service.getAccessToken() },
    contentType: 'application/json',
    payload: JSON.stringify(message),
  });
}

事件驅動觸發條件

可安裝的事件驅動觸發事件在概念上與 onOpen()簡易觸發事件相似,但可回應其他事件,且行為有所不同。

舉例來說,只要有編輯權限的使用者開啟試算表,Google 試算表的啟用觸發條件就會啟用,就像簡單的 onOpen() 觸發條件一樣。不過,可安裝版本可以呼叫需要授權服務。即使其他具有編輯權限的使用者開啟試算表,安裝版本也會在建立觸發條件的使用者授權下執行。

Google Workspace 應用程式有幾種可安裝的觸發條件:

您可以在獨立和已繫結的指令碼中使用可安裝的觸發條件。舉例來說,獨立指令碼可以透過程式碼為任意 Google 試算表檔案建立可安裝的觸發事件,方法是呼叫 TriggerBuilder.forSpreadsheet(key) 並傳入試算表的 ID。

手動管理觸發條件

如要在指令碼編輯器中手動建立可安裝的觸發條件,請按照下列步驟操作:

  1. 開啟 Apps Script 專案。
  2. 按一下左側的「觸發條件」圖示 。
  3. 按一下右下方的「新增觸發條件」。
  4. 選取並設定要建立的觸發條件類型。
  5. 按一下 [儲存]。

以程式輔助方式管理觸發條件

您也可以使用 Script 服務,以程式輔助的方式建立及刪除觸發條件。首先呼叫 ScriptApp.newTrigger(functionName),該函式會傳回 TriggerBuilder

以下範例說明如何建立兩個時間觸發事件,一個是每 6 小時觸發一次,另一個是每週一上午 9 點觸發一次 (以指令碼設定的時區為準)。

以下範例說明如何為試算表建立可安裝的開啟觸發條件。請注意,與簡單的 onOpen() 觸發條件不同,可安裝觸發條件的指令碼不需要綁定至試算表。如要透過獨立指令碼建立此觸發事件,只需將 SpreadsheetApp.getActive() 替換為對 SpreadsheetApp.openById(id) 的呼叫即可。

如要透過程式輔助方式修改現有的可安裝觸發條件,您必須先刪除該觸發條件,再建立新的觸發條件。如果您先前儲存了觸發事件的 ID,可以將 ID 做為引數傳遞至下列函式,藉此刪除該 ID。

建立觸發事件前,建議您確認相關聯的函式是否具備所有必要的 OAuth 權限

觸發條件中的錯誤

當可安裝的觸發事件觸發,但函式擲回例外狀況或無法順利執行時,畫面上不會顯示錯誤訊息。畢竟,當時間觸發條件執行或其他使用者啟用表單提交觸發條件時,您可能不在電腦前。

相反地,應用程式指令碼會傳送以下電子郵件給你:

From: noreply-apps-scripts-notifications@google.com Subject: Summary of failures for Google Apps Script Your script has recently failed to finish successfully. A summary of the failure(s) is shown below.

電子郵件中會附上停用或重新設定觸發條件的連結。如果指令碼繫結至 Google 試算表、文件或表單檔案,電子郵件也會附上該檔案的連結。這些連結可讓您停用觸發條件或編輯指令碼,以修正錯誤。

如要查看與 Google 帳戶相關聯的所有觸發條件,並停用不再需要的觸發條件,請按照下列步驟操作:

  1. 前往 script.google.com
  2. 按一下左側的「我的觸發條件」。
  3. 如要刪除觸發條件,請依序按一下觸發條件右側的「更多」圖示 >「刪除觸發條件」。

外掛程式中的觸發條件

除了可安裝的觸發事件之外,您也可以在外掛程式中使用資訊清單觸發事件。詳情請參閱「Google Workspace 外掛程式的觸發條件」。