本指南說明如何使用webhook,讓您的對話方塊更具彈性。Cloud Functions 可用於代管 webhook,因為這項服務相當簡單,但您也可以透過許多其他方式代管 webhook 服務。這個範例也使用 Go 程式設計語言,但您可以使用任何Cloud Functions 支援的語言。您不需要編輯本指南的程式碼。
以下 webhook 程式碼範例會執行下列作業:
- 讀取 Webhook 要求中的參數值。
- 將參數值寫入 webhook 回應。
- 在 Webhook 回應中提供文字回應。
事前準備
如果您不打算使用 webhook,可以略過本快速入門導覽課程。
閱讀本指南之前,請先完成下列工作:
- 請參閱流程基本概念。
- 執行設定步驟。
- 執行使用流程建構代理程式快速入門指南中的步驟。以下步驟將繼續處理同一個代理程式。如果您已找不到該代理程式,可以下載代理程式並還原。
建立 Cloud 函式
您可以使用 Google Cloud 控制台建立 Cloud Functions (參閱說明文件,開啟控制台)。如要為本指南建立函式,請按照下列步驟操作:
- 請務必將 Conversational Agents (Dialogflow CX) 服務專員和函式放在同一個專案中。這是 Conversational Agents (Dialogflow CX) 安全存取函式最簡單的方式。如要選取專案,請前往專案選取器。
- 前往 Cloud Functions 總覽頁面。
- 按一下「建立函式」,然後設定下列欄位:
- 環境:第 1 代
- 函式名稱:shirts-agent-webhook
- 地區:如果您為服務專員指定了地區,請使用相同的地區。
- HTTP 觸發條件類型:HTTP
- 網址:按一下這裡的複製按鈕,然後儲存值。設定 Webhook 時,您需要使用這個網址。
- 驗證:需要驗證
- 「必須使用 HTTPS」:已勾選
- 按一下 [儲存]。
- 按一下「Next」 (您不需要特殊的執行階段、建構作業、連線或安全性設定)。
- 設定下列欄位:
- Runtime:選取最新的 Go 執行階段。
- 原始碼:內嵌編輯器
- 進入點:HandleWebhookRequest
將程式碼替換為以下內容:
// Package cxwh contains an example Dialogflow CX webhook package cxwh import ( "encoding/json" "fmt" "log" "net/http" ) type fulfillmentInfo struct { Tag string `json:"tag"` } type sessionInfo struct { Session string `json:"session"` Parameters map[string]interface{} `json:"parameters"` } type text struct { Text []string `json:"text"` } type responseMessage struct { Text text `json:"text"` } type fulfillmentResponse struct { Messages []responseMessage `json:"messages"` } // webhookRequest is used to unmarshal a WebhookRequest JSON object. Note that // not all members need to be defined--just those that you need to process. // As an alternative, you could use the types provided by the Dialogflow protocol buffers: // https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3#WebhookRequest type webhookRequest struct { FulfillmentInfo fulfillmentInfo `json:"fulfillmentInfo"` SessionInfo sessionInfo `json:"sessionInfo"` } // webhookResponse is used to marshal a WebhookResponse JSON object. Note that // not all members need to be defined--just those that you need to process. // As an alternative, you could use the types provided by the Dialogflow protocol buffers: // https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/dialogflow/cx/v3#WebhookResponse type webhookResponse struct { FulfillmentResponse fulfillmentResponse `json:"fulfillmentResponse"` SessionInfo sessionInfo `json:"sessionInfo"` } // confirm handles webhook calls using the "confirm" tag. func confirm(request webhookRequest) (webhookResponse, error) { // Create a text message that utilizes the "size" and "color" // parameters provided by the end-user. // This text message is used in the response below. t := fmt.Sprintf("You can pick up your order for a %s %s shirt in 5 days.", request.SessionInfo.Parameters["size"], request.SessionInfo.Parameters["color"]) // Create session parameters that are populated in the response. // The "cancel-period" parameter is referenced by the agent. // This example hard codes the value 2, but a real system // might look up this value in a database. p := map[string]interface{}{"cancel-period": "2"} // Build and return the response. response := webhookResponse{ FulfillmentResponse: fulfillmentResponse{ Messages: []responseMessage{ { Text: text{ Text: []string{t}, }, }, }, }, SessionInfo: sessionInfo{ Parameters: p, }, } return response, nil } // handleError handles internal errors. func handleError(w http.ResponseWriter, err error) { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "ERROR: %v", err) } // HandleWebhookRequest handles WebhookRequest and sends the WebhookResponse. func HandleWebhookRequest(w http.ResponseWriter, r *http.Request) { var request webhookRequest var response webhookResponse var err error // Read input JSON if err = json.NewDecoder(r.Body).Decode(&request); err != nil { handleError(w, err) return } log.Printf("Request: %+v", request) // Get the tag from the request, and call the corresponding // function that handles that tag. // This example only has one possible tag, // but most agents would have many. switch tag := request.FulfillmentInfo.Tag; tag { case "confirm": response, err = confirm(request) default: err = fmt.Errorf("Unknown tag: %s", tag) } if err != nil { handleError(w, err) return } log.Printf("Response: %+v", response) // Send response if err = json.NewEncoder(w).Encode(&response); err != nil { handleError(w, err) return } }
按一下 [Deploy] (部署)。
等待狀態指標顯示函式已成功部署。等待期間,請檢查剛部署的程式碼。程式碼註解會說明重要細節。
建立 Webhook
Webhook 現已成為 Cloud 函式,您可以將此 webhook 與服務機器人建立關聯。如要為代理程式建立 Webhook,請按照下列步驟操作:
- 開啟 Dialogflow CX 控制台。
- 選擇 Google Cloud 專案。
- 選取代理程式。
- 選取「管理」分頁標籤。
- 按一下「Webhook」。
- 按一下 [建立]。
- 填寫下列欄位:
- 顯示名稱:shirts-agent-webhook
- Webhook 網址:提供建立函式時儲存的 Webhook 網址。
- 子類型:標準。
- 其他欄位則使用預設值。
- 按一下 [儲存]。
使用 Webhook
由於現在可讓服務代理使用 webhook,您將在執行要求中使用 webhook。「Order Confirmation」頁面有一個輸入完成項目,目前有靜態文字回應。如要更新執行要求以使用 Webhook,請按照下列步驟操作:
- 選取「Build」分頁標籤。
- 按一下「訂單確認」頁面,在代理程式建構工具圖表中展開該頁面。
- 按一下頁面上的「Entry Fulfillment」欄位,開啟執行要求面板。
- 刪除「Agent says」標題下方的現有文字回應。當您將滑鼠游標懸停在文字上時,系統會顯示刪除 delete 按鈕。
- 按一下「啟用 webhook」。
- 從「Webhook」下拉式選單中選取「
shirts-agent-webhook
」選項。 - 在「Tag」欄位中輸入
confirm
。 - 按一下 [儲存]。
- 關閉「執行」面板。
已部署的 Webhook 程式碼會傳送回應,建立名為 cancel-period
的參數。請更新代理程式,在相同的「訂單確認」頁面中,在最終代理程式回應中參照這個參數:
- 按一下顯示
true
條件的「路線」條件,開啟路線面板。 - 向下捲動至路由面板的「Fulfillment」部分,然後在「Agent says」標題下方新增下列文字回應:
You can cancel your order within $session.params.cancel-period days. Goodbye.
- 按一下 [儲存]。
- 關閉路線面板。
在模擬工具中測試代理程式
代理程式和 Webhook 都已準備就緒,可透過模擬工具進行測試:
- 按一下「Test Agent」。
- 輸入
I want to buy a large red shirt
並按下 Enter 鍵。
由於你同時提供尺寸和顏色,因此已提供代理人建立襯衫訂單所需的所有資訊,因此系統會直接轉到「訂單確認」頁面。
以下說明服務專員的回應:
回應 | 說明 |
---|---|
好的,我們來建立新的訂單。 | 當「New Order」頁面啟用時,系統會呼叫項目執行作業。回應是由這個執行要求觸發。 |
你選取了紅色大尺寸的襯衫。 | 為「New Order」頁面提供所有表單參數後,系統會呼叫檢查表單是否已完成的條件路徑。回應是透過此路徑的執行要求觸發。這個路徑也會轉換至「訂單確認」頁面。 |
你可以在 5 天內領取訂購的紅色大尺寸上衣。 | 「Order Confirmation」頁面的輸入完成動作會呼叫 Webhook。請參閱 webhook 程式碼中的 confirm 函式。該函式會建立此文字回應,並使用 webhook 要求中提供的參數。 |
你可以在 2 天內取消訂單。Goodbye. | 「Order Confirmation」頁面包含條件路徑,其中條件一律為 true。這項回應是由該路徑的執行要求觸發。請注意,回應會使用 webhook 在 webhook 回應中設定的參數。 |