可安裝的觸發條件

如同簡易觸發條件,可安裝的觸發條件可讓 Apps Script 在發生特定事件 (例如開啟文件) 時,自動執行函式。不過,可安裝觸發條件比簡單的觸發條件更具彈性:這類觸發條件能夠呼叫需要授權服務。這類觸發條件提供時間導向 (時鐘) 觸發事件等多種額外事件,且這些觸發條件可透過程式輔助方式控管。無論是簡單或可安裝的觸發條件,Apps Script 都會傳送已觸發函式的事件物件,其中包含事件發生情境的資訊。

限制

即使可安裝的觸發條件比簡單的觸發條件更具彈性,但仍須遵守一些限制:

  • 如果檔案是以唯讀 (檢視或註解) 模式開啟,就不會執行。獨立指令碼的使用者至少必須具備指令碼檔案的檢視權限,觸發條件才能正常運作。
  • 指令碼執行和 API 要求不會導致觸發條件執行。舉例來說,呼叫 FormResponse.submit() 來提交新的表單回應,並不會導致表單的提交觸發條件執行。

  • 可安裝觸發條件一律會在建立觸發條件的使用者帳戶下執行。舉例來說,如果您建立了可安裝的開啟觸發條件,當同事開啟文件 (前提是您的同事具有編輯權限) 就會執行這個觸發條件,但會以帳戶的形式執行。也就是說,如果您建立在開啟文件時傳送電子郵件的觸發條件,系統一律會從您的帳戶寄出電子郵件,不一定是開啟文件的帳戶。不過,您可以為各個帳戶建立可安裝的觸發條件,這樣就會為每個帳戶傳送一封電子郵件。

  • 特定帳戶無法查看從第二個帳戶安裝的觸發條件,即使第一個帳戶仍可啟用這些觸發條件。

  • 可安裝的觸發條件適用 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,透過程式輔助方式為任意 Google 試算表檔案建立可安裝的觸發條件。

手動管理觸發條件

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

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

透過程式輔助方式管理觸發條件

您也可以透過指令碼服務,以程式輔助的方式建立及刪除觸發條件。首先,呼叫 ScriptApp.newTrigger(functionName) 來傳回 TriggerBuilder

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

triggers/triggers.gs
/**
 * Creates two time-driven triggers.
 * @see https://developers.google.com/apps-script/guides/triggers/installable#time-driven_triggers
 */
function createTimeDrivenTriggers() {
  // Trigger every 6 hours.
  ScriptApp.newTrigger('myFunction')
      .timeBased()
      .everyHours(6)
      .create();
  // Trigger every Monday at 09:00.
  ScriptApp.newTrigger('myFunction')
      .timeBased()
      .onWeekDay(ScriptApp.WeekDay.MONDAY)
      .atHour(9)
      .create();
}

下一個範例說明如何為試算表建立可安裝的開啟觸發條件。請注意,與簡易 onOpen() 觸發條件不同的是,可安裝觸發條件的指令碼不需要繫結至試算表。如要從獨立指令碼建立這個觸發條件,只要將 SpreadsheetApp.getActive() 替換為呼叫 SpreadsheetApp.openById(id) 即可。

triggers/triggers.gs
/**
 * Creates a trigger for when a spreadsheet opens.
 * @see https://developers.google.com/apps-script/guides/triggers/installable
 */
function createSpreadsheetOpenTrigger() {
  const ss = SpreadsheetApp.getActive();
  ScriptApp.newTrigger('myFunction')
      .forSpreadsheet(ss)
      .onOpen()
      .create();
}

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

triggers/triggers.gs
/**
 * Deletes a trigger.
 * @param {string} triggerId The Trigger ID.
 * @see https://developers.google.com/apps-script/guides/triggers/installable
 */
function deleteTrigger(triggerId) {
  // Loop over all triggers.
  const allTriggers = ScriptApp.getProjectTriggers();
  for (let index = 0; index < allTriggers.length; index++) {
    // If the current trigger is the correct one, delete it.
    if (allTriggers[index].getUniqueId() === triggerId) {
      ScriptApp.deleteTrigger(allTriggers[index]);
      break;
    }
  }
}

觸發條件發生錯誤

當可安裝的觸發條件啟動時,但函式擲回例外狀況或無法成功執行,畫面上就不會出現錯誤訊息。畢竟,當時間驅動的觸發條件執行,或其他使用者啟用您的表單提交觸發條件時,您甚至可能沒有回到電腦。

而是會透過電子郵件將下列內容傳送給您:

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 外掛程式的觸發條件」一文。