1. 簡介
Google Chat 擴充應用程式可將服務和資源直接帶入 Chat,讓使用者在對話中取得資訊並採取行動。
在本程式碼研究室中,您將瞭解如何建立 Chat 應用程式「Attendance Chat app」,在 Gmail 中設定休假回覆,並在 Google 日曆中安排會議。在 Google Apps Script 中建構 Attendance Chat 應用程式,即可輕鬆存取其他 Google 服務,例如雲端硬碟、Gmail、日曆、文件、試算表等。
課程內容
- 如何新增處理常式來處理 Chat 中引發的事件
- 如何剖析從 Chat 傳送的事件物件
- 如何以卡片格式回覆 Chat
- 如何定義及回應資訊卡中按鈕點擊的自訂動作
軟硬體需求
- 可連上網際網路並具備網路瀏覽器。
- 具有 Google Chat 存取權的 Google Workspace 帳戶。
- 具備 JavaScript 基礎知識:Google Apps Script 僅支援 JavaScript。
2. 取得程式碼範例
您可以下載 ZIP 檔案或複製 GitHub 存放區,查看這個範例中每個步驟的程式碼。
solutions/attendance-chat-app
下的 step-NN
資料夾包含本程式碼研究室各個步驟的所需最終狀態。僅供參考。
下載程式碼
如要下載本程式碼研究室的程式碼,請按一下下列按鈕:
將下載的 ZIP 檔案解壓縮。這會解壓縮根資料夾 (apps-script-samples
),其中包含 solutions/attendance-chat-app
下本程式碼研究室每個步驟的資料夾。
複製 GitHub 存放區
如要複製本程式碼研究室的 GitHub 存放區,請執行下列指令:
git clone https://github.com/googleworkspace/apps-script-samples
3. 建立 Google Chat 事件的處理常式
建立 Apps Script 專案
如要建立 Apps Script 專案,請按照下列步驟操作:
- 前往 script.new。
- 按一下「未命名專案」。
- 將指令碼重新命名為「Attendance Chat app」,然後按一下「重新命名」。
Google Chat 中的活動
Apps Script 與 Chat 的互動大多是由事件觸發。使用者、Chat 應用程式和 Chat 之間的互動通常會依下列順序進行:
- 使用者發起動作,例如將 Chat 應用程式新增至聊天室、發起與 Chat 應用程式的即時訊息 (DM),或從聊天室中移除 Chat 應用程式。
- 這項動作會針對 Chat 中的 Chat 應用程式引發事件。
- Chat 會呼叫 Chat 應用程式指令碼中定義的對應事件處理常式。
Chat 會發出 4 個事件,供應用程式監聽:
ADDED_TO_SPACE
:當使用者將 Chat 應用程式新增至聊天室或即時訊息時,就會發生這個事件。在 Apps Script 中,您可以定義onAddToSpace()
函式來處理這項事件。REMOVED_FROM_SPACE
:使用者從聊天室或即時訊息中移除 Chat 應用程式時,就會發生這個事件。這個事件不會將回覆發布回 Chat。在 Apps Script 中,您可以定義onRemoveFromSpace()
函式來處理這項事件。MESSAGE
:使用者透過即時訊息直接傳送訊息給 Chat 應用程式,或在聊天室中使用 @符號提及 Chat 應用程式時,就會觸發這個事件。在 Apps Script 中,您可以定義onMessage()
函式來回應這個事件。CARD_CLICKED
:使用者點選已指派自訂動作的按鈕時,就會發生這個事件。在 Apps Script 中,您可以定義onCardClick()
函式來回應這個事件。
將 Code.gs
檔案的內容替換為下列程式碼,定義 ADDED_TO_SPACE
和 REMOVE_FROM_SPACE
事件的處理常式。(您將在本程式碼研究室稍後新增 MESSAGE
和 CARD_CLICKED
事件的處理常式)。
Code.gs
/**
* Responds to an ADDED_TO_SPACE event in Google Chat.
* @param {object} event the event object from Google Chat
* @return {object} JSON-formatted response
* @see https://developers.google.com/workspace/chat/receive-respond-interactions
*/
function onAddToSpace(event) {
console.info(event);
var message = 'Thank you for adding me to ';
if (event.space.type === 'DM') {
message += 'a DM, ' + event.user.displayName + '!';
} else {
message += event.space.displayName;
}
return { text: message };
}
/**
* Responds to a REMOVED_FROM_SPACE event in Google Chat.
* @param {object} event the event object from Google Chat
* @see https://developers.google.com/workspace/chat/receive-respond-interactions
*/
function onRemoveFromSpace(event) {
console.info(event);
console.log('Chat app removed from ', event.space.name);
}
4. 發布及測試 Chat 應用程式
更新指令碼資訊清單檔案
如要將應用程式發布至 Chat,請務必先更新指令碼資訊清單。
- 按一下「專案設定」圖示
。
- 勾選「在編輯器中顯示『appsscript.json』資訊清單檔案」核取方塊。
- 按一下「編輯器」
。
- 按一下
appsscript.json
檔案。 - 在資訊清單檔案中新增
"chat": {}
這行程式碼。
您的資訊清單檔案應與下列範例類似。
appsscript.json
{
"timeZone": "America/Los_Angeles",
"dependencies": {
},
"chat": {}
}
建立 Google Cloud 專案
如要執行及測試 Chat 應用程式,您必須先建立 Google Cloud 專案、啟用及設定 Chat API,然後將 Chat 應用程式發布至 Google Workspace 機構。
- 在 Google Cloud 控制台中,依序前往「選單」圖示
>「IAM 與管理」>「建立專案」。
- 在「專案名稱」部分輸入描述性名稱。
- 如果系統提示,請選取「機構」和「帳單帳戶」。
- 點選「建立」。
- 專案建立完成後,頁面右上角會顯示通知。按一下「Create Project: <Project name>」(建立專案:<專案名稱>) 項目,開啟專案。
- 依序點選「選單」圖示
>「API 和服務」>「憑證」。
- 按一下 [OAuth consent screen] (OAuth 同意畫面)。
- 在「應用程式名稱」部分,輸入「Attendance Chat app」。
- 如果系統提示,請輸入使用者支援電子郵件地址和開發人員聯絡資訊。
- 按一下 [儲存並繼續]。
- 依序點選「設定和公用程式」圖示
>「專案設定」。
- 複製專案編號。
- 返回 Apps Script 編輯器,然後按一下「專案設定」圖示
。
- 在「Google Cloud Platform (GCP) 專案」下方,按一下「變更專案」。
- 按一下「GCP 專案編號」,然後輸入專案編號。
- 按一下「設定專案」。
將應用程式發布到 Chat
如要將 Chat 擴充應用程式發布至 Google Chat,請按照下列步驟操作:
- 在 Apps Script 編輯器中,依序點選「部署」>「新增部署作業」。
- 按一下「選取類型」旁的「啟用部署類型」圖示
。
- 選取「外掛程式」,然後按一下「部署」。
- 複製「部署作業 ID」,然後按一下「完成」。
- 前往 Google Cloud 控制台,依序點選「選單」圖示
>「API 和服務」>「程式庫」。
- 搜尋「Google Chat API」。從結果清單中選取 API。
- 在 Google Chat API 頁面中,按一下「啟用」。
- 啟用 API 後,按一下「設定」。請忽略要求您建立憑證的訊息。
- 在「設定」頁面中,執行下列操作:
- 在「應用程式名稱」部分,輸入「Attendance Chat app」。
- 在「Avatar URL」部分輸入 https://goo.gl/kv2ENA。
- 在「說明」中,輸入「Apps Script codelab Chat app」。
- 在「功能」下方,選取「接收一對一訊息」。
- 在「連結設定」下方,選取「Apps Script 專案」,然後將指令碼的部署 ID 貼到文字方塊中。
- 在「權限」下方,選取「僅限您網域中的特定使用者和群組」。在下拉式選單下方的文字方塊中,輸入與 Google Workspace 機構相關聯的電子郵件地址。
- 按一下 [儲存]。
儲存變更後,請確認 Google Chat API 頁面的「應用程式狀態」顯示為「已發布 - 使用者可存取」。
測試 Chat 應用程式
如要在 Google Chat 中測試應用程式,請按照下列步驟操作:
- 開啟 Google Chat。
- 按一下「發起即時通訊」圖示
>「尋找應用程式」,向 Chat 應用程式傳送新的即時訊息。
- 在「尋找應用程式」頁面中,搜尋「Attendance Chat app」。
- 在「Attendance Chat 應用程式」旁,依序點選「新增」>「Chat」。
開啟即時訊息串後,您應該會看到 Chat 應用程式傳送的訊息,感謝您將其新增至即時訊息,如下圖所示。
5. 定義卡片格式的回覆
在上一個步驟中,您的應用程式以簡單的文字回覆回應 Google Chat 事件。在這個步驟中,您要更新應用程式,以便回覆資訊卡。
回覆卡片
Google Chat 支援使用資訊卡回覆訊息。資訊卡是視覺容器,可將一組使用者介面小工具分組。資訊卡可顯示標題、文字段落、按鈕組合、圖片和鍵/值文字。應用程式可以在傳送給 Google Chat 的 JSON 回應中定義一或多張資訊卡,Google Chat 隨後會將回覆內容轉換為對應的 UI 元素。
下圖顯示含有三個部分的資訊卡回覆,包括標題、鍵/值小工具、圖片小工具和文字按鈕。
如要使用資訊卡回覆使用者訊息,請在 Chat 應用程式的 Code.gs
檔案中新增下列程式碼。
Code.gs
const DEFAULT_IMAGE_URL = 'https://goo.gl/bMqzYS';
const HEADER = {
header: {
title : 'Attendance Chat app',
subtitle : 'Log your vacation time',
imageUrl : DEFAULT_IMAGE_URL
}
};
/**
* Creates a card-formatted response.
* @param {object} widgets the UI components to send
* @return {object} JSON-formatted response
*/
function createCardResponse(widgets) {
return {
cards: [HEADER, {
sections: [{
widgets: widgets
}]
}]
};
}
/**
* Responds to a MESSAGE event triggered
* in Google Chat.
*
* @param event the event object from Google Chat
* @return JSON-formatted response
*/
function onMessage(event) {
const userMessage = event.message.text;
const widgets = [{
"textParagraph": {
"text": "You said: " + userMessage
}
}];
return createCardResponse(widgets);
}
這個步驟新增的 onMessage()
函式會讀取使用者的原始訊息,並建構簡單的 TextParagragh 小工具做為回覆。接著,onMessage()
函式會呼叫 createCardResponse()
,將 TextParagraph 小工具放在單一資訊卡的某個區段中。Chat 應用程式會將以卡片回覆建構的 JavaScript 物件傳回 Google Chat。
測試 Chat 應用程式
如要測試這個應用程式,請返回 Google Chat 中與該應用程式的即時訊息,然後輸入訊息 (任何訊息都可以)。
請注意,onMessage()
事件處理常式會剖析 Google Chat 傳遞給它的事件物件,以擷取使用者的原始訊息。您也可以取得其他類型的事件資訊,包括發起事件的使用者名稱、電子郵件地址、發生事件的空間名稱等。
如要進一步瞭解 Google Chat 傳送的事件物件結構,請參閱「事件格式參考資料」。
6. 對資訊卡中的按鈕點擊動作做出回應
在上一個步驟中,您的 Chat 應用程式已透過含有 TextParagragh 小工具的簡單資訊卡,回應使用者傳送的訊息 (MESSAGE
事件)。在這個步驟中,您會建立包含按鈕的回覆,每個按鈕都有自訂動作。
互動式資訊卡
資訊卡回覆可包含兩種按鈕:顯示純文字按鈕的文字按鈕小工具,以及顯示含有簡單圖示或圖片 (不含文字) 按鈕的 ImageButton 小工具。TextButton 和 ImageButton 小工具都支援兩種 onClick
行為 (如傳回 Google Chat 的 JSON 回應中所定義):openLink
或 action
。顧名思義,openLink
會在新瀏覽器分頁中開啟指定連結。
action
物件會指定按鈕要執行的自訂動作。您可以在動作物件中指定多個任意值,包括專屬 actionMethodName
和一組鍵 / 值參數組合。
為按鈕指定 action
物件,即可建立互動式資訊卡。使用者點選訊息中的按鈕時,Google Chat 會引發 CARD_CLICKED
事件,並將要求傳回給傳送原始訊息的應用程式。接著,應用程式必須處理 Google Chat 提出的事件,並將回覆傳回聊天室。
將 Code.gs
中的 onMessage()
函式替換為以下程式碼。這段程式碼會在傳送至 Google Chat 的資訊卡中,建立 2 個按鈕:「在 Gmail 中設定休假」和「在 Google 日曆中封鎖當天行程」。
Code.gs
const REASON = {
SICK: 'Out sick',
OTHER: 'Out of office'
};
/**
* Responds to a MESSAGE event triggered in Google Chat.
* @param {object} event the event object from Google Chat
* @return {object} JSON-formatted response
*/
function onMessage(event) {
console.info(event);
const reason = REASON.OTHER;
const name = event.user.displayName;
const userMessage = event.message.text;
// If the user said that they were 'sick', adjust the image in the
// header sent in response.
if (userMessage.indexOf('sick') > -1) {
// Hospital material icon
HEADER.header.imageUrl = 'https://goo.gl/mnZ37b';
reason = REASON.SICK;
} else if (userMessage.indexOf('vacation') > -1) {
// Spa material icon
HEADER.header.imageUrl = 'https://goo.gl/EbgHuc';
}
const widgets = [{
textParagraph: {
text: 'Hello, ' + name + '.<br/>Are you taking time off today?'
}
}, {
buttons: [{
textButton: {
text: 'Set vacation in Gmail',
onClick: {
action: {
actionMethodName: 'turnOnAutoResponder',
parameters: [{
key: 'reason',
value: reason
}]
}
}
}
}, {
textButton: {
text: 'Block out day in Calendar',
onClick: {
action: {
actionMethodName: 'blockOutCalendar',
parameters: [{
key: 'reason',
value: reason
}]
}
}
}
}]
}];
return createCardResponse(widgets);
}
如要處理 CARD_CLICKED
事件,請務必在 Chat 應用程式的指令碼中加入 onCardClick()
函式。新增下列程式碼,定義 onCardClick()
函式 Code.gs
。
Code.gs
/**
* Responds to a CARD_CLICKED event triggered in Google Chat.
* @param {object} event the event object from Google Chat
* @return {object} JSON-formatted response
* @see https://developers.google.com/workspace/chat/receive-respond-interactions
*/
function onCardClick(event) {
console.info(event);
let message = '';
const reason = event.action.parameters[0].value;
if (event.action.actionMethodName == 'turnOnAutoResponder') {
turnOnAutoResponder(reason);
message = 'Turned on vacation settings.';
} else if (event.action.actionMethodName == 'blockOutCalendar') {
blockOutCalendar(reason);
message = 'Blocked out your calendar for the day.';
} else {
message = "I'm sorry; I'm not sure which button you clicked.";
}
return { text: message };
}
現在,Chat 應用程式在回應使用者點擊時,會執行下列其中一項操作:將使用者在 Gmail 中的自動回覆設為「不在辦公室」訊息,或在使用者日曆中安排全天會議。如要完成這些工作,應用程式會呼叫 Gmail 進階服務和 Google 日曆服務。
在指令碼中加入下列程式碼,將 Chat 應用程式與 Gmail 和 Google 日曆整合。
Code.gs
const ONE_DAY_MILLIS = 24 * 60 * 60 * 1000;
/**
* Turns on the user's vacation response for today in Gmail.
* @param {string} reason the reason for vacation, either REASON.SICK or REASON.OTHER
*/
function turnOnAutoResponder(reason) {
let currentTime = (new Date()).getTime();
Gmail.Users.Settings.updateVacation({
enableAutoReply: true,
responseSubject: reason,
responseBodyHtml: "I'm out of the office today; will be back on the next business day.<br><br><i>Created by Attendance Chat app!</i>",
restrictToContacts: true,
restrictToDomain: true,
startTime: currentTime,
endTime: currentTime + ONE_DAY_MILLIS
}, 'me');
}
/**
* Places an all-day meeting on the user's Calendar.
* @param {string} reason the reason for vacation, either REASON.SICK or REASON.OTHER
*/
function blockOutCalendar(reason) {
CalendarApp.createAllDayEvent(reason, new Date(), new Date(Date.now() + ONE_DAY_MILLIS));
}
最後,您必須在專案中啟用 Gmail 進階服務。如要啟用 Gmail API,請按照下列步驟操作:
- 在 Apps Script 編輯器中,按一下「服務」旁邊的「新增服務」圖示
。
- 選取「Gmail API」。
- 點選下方的「Google Cloud Platform API 資訊主頁」,開啟 Google Cloud Console。
- 點選「啟用 API 和服務」。
- 搜尋「Gmail API」,然後按一下「Gmail API」。
- 在 Gmail API 頁面中,按一下「啟用」。
測試 Chat 應用程式
如要測試這個版本的 Chat 應用程式,請在 Google Chat 中開啟您在先前步驟中發起的即時通訊,然後輸入「我要去度假」。應用程式應會回覆類似下圖的資訊卡。
注意:如果系統要求您提供應用程式存取權,您可能需要再次輸入訊息。
7. 恭喜!
現在,Chat 應用程式可以回覆使用者訊息、在 Gmail 中設定自動回覆,以及在 Google 日曆中新增全天活動。
涵蓋內容
- 使用 Apps Script 建立並發布 Google Chat 擴充應用程式
- 以簡單的回覆內容回應使用者訊息
- 透過 Chat 應用程式代表使用者與其他 Google Workspace 服務互動