创建网络钩子服务

您在上一步中创建的预建代理无法提供帐号余额等动态数据,因为所有内容都已硬编码到该代理中。在教程的此步骤中,您将创建一个可以为代理提供动态数据的网络钩子。本教程中使用 Cloud Functions 来托管 webhook,因为它简单易用。不过,您还可以通过其他许多方式托管 webhook 服务。该示例也使用 Go 编程语言,但您可以使用 Cloud Functions 支持的语言

创建函数

您可以通过 Google Cloud 控制台创建 Cloud Functions 函数(查看文档打开控制台)。如需为本教程创建函数,请执行以下操作:

  1. 您的 Dialogflow 代理和函数必须位于同一项目中,这一点非常重要。这是 Dialogflow 要安全访问函数的最简单方法。在创建函数之前,请从 Google Cloud 控制台中选择您的项目。

    转到“项目选择器”

  2. 打开 Cloud Functions 概览页面。

    转到 Cloud Functions 概览

  3. 点击创建函数,并设置以下字段:

    • 环境:第 1 代
    • 函数名称:tutorials-banking-webhook
    • 区域:如果您为代理指定了区域,请使用同一区域。
    • HTTP Trigger type:HTTP
    • 网址:点击此处的复制按钮并保存相应的值。 配置 webhook 时需要使用此网址。
    • Authentication:需要身份验证
    • Require HTTPS(需要 HTTPS):选中
  4. 点击保存

  5. 点击下一步(您不需要特殊的运行时、构建、连接或安全设置)。

  6. 设置以下字段:

    • Runtime:选择最新的 Go 运行时。
    • 源代码:内嵌编辑器
    • 入口点:HandleWebhookRequest
  7. 将代码替换为以下代码:

    package estwh
    
    import (
    	"context"
    	"encoding/json"
    	"fmt"
    	"log"
    	"net/http"
    	"os"
    	"strings"
    
    	"cloud.google.com/go/spanner"
      "google.golang.org/grpc/codes"
    )
    
    // client is a Spanner client, created only once to avoid creation
    // for every request.
    // See: https://cloud.google.com/functions/docs/concepts/go-runtime#one-time_initialization
    var client *spanner.Client
    
    func init() {
    	// If using a database, these environment variables will be set.
    	pid := os.Getenv("PROJECT_ID")
    	iid := os.Getenv("SPANNER_INSTANCE_ID")
    	did := os.Getenv("SPANNER_DATABASE_ID")
    	if pid != "" && iid != "" && did != "" {
    		db := fmt.Sprintf("projects/%s/instances/%s/databases/%s",
    			pid, iid, did)
    		log.Printf("Creating Spanner client for %s", db)
    		var err error
    		// Use the background context when creating the client,
    		// but use the request context for calls to the client.
    		// See: https://cloud.google.com/functions/docs/concepts/go-runtime#contextcontext
    		client, err = spanner.NewClient(context.Background(), db)
    		if err != nil {
    			log.Fatalf("spanner.NewClient: %v", err)
    		}
    	}
    }
    
    type queryResult struct {
    	Action     string                 `json:"action"`
    	Parameters map[string]interface{} `json:"parameters"`
    }
    
    type text struct {
    	Text []string `json:"text"`
    }
    
    type message struct {
    	Text text `json:"text"`
    }
    
    // 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://godoc.org/google.golang.org/genproto/googleapis/cloud/dialogflow/v2#WebhookRequest
    type webhookRequest struct {
    	Session     string      `json:"session"`
    	ResponseID  string      `json:"responseId"`
    	QueryResult queryResult `json:"queryResult"`
    }
    
    // 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://godoc.org/google.golang.org/genproto/googleapis/cloud/dialogflow/v2#WebhookResponse
    type webhookResponse struct {
    	FulfillmentMessages []message `json:"fulfillmentMessages"`
    }
    
    // accountBalanceCheck handles the similar named action
    func accountBalanceCheck(ctx context.Context, request webhookRequest) (
    	webhookResponse, error) {
    	account := request.QueryResult.Parameters["account"].(string)
    	account = strings.ToLower(account)
    	var table string
    	if account == "savings account" {
    		table = "Savings"
    	} else {
    		table = "Checking"
    	}
    	s := "Your balance is $0"
    	if client != nil {
    		// A Spanner client exists, so access the database.
    		// See: https://pkg.go.dev/cloud.google.com/go/spanner#ReadOnlyTransaction.ReadRow
    		row, err := client.Single().ReadRow(ctx,
    			table,
    			spanner.Key{1}, // The account ID
    			[]string{"Balance"})
    		if err != nil {
    			if spanner.ErrCode(err) == codes.NotFound {
    				log.Printf("Account %d not found", 1)
    			} else {
    				return webhookResponse{}, err
    			}
    		} else {
    			// A row was returned, so check the value
    			var balance int64
    			err := row.Column(0, &balance)
    			if err != nil {
    				return webhookResponse{}, err
    			}
    			s = fmt.Sprintf("Your balance is $%.2f", float64(balance)/100.0)
    		}
    	}
    	response := webhookResponse{
    		FulfillmentMessages: []message{
    			{
    				Text: text{
    					Text: []string{s},
    				},
    			},
    		},
    	}
    	return response, nil
    }
    
    // Define a type for handler functions.
    type handlerFn func(ctx context.Context, request webhookRequest) (
    	webhookResponse, error)
    
    // Create a map from action to handler function.
    var handlers map[string]handlerFn = map[string]handlerFn{
    	"account.balance.check": accountBalanceCheck,
    }
    
    // handleError handles internal errors.
    func handleError(w http.ResponseWriter, err error) {
    	log.Printf("ERROR: %v", err)
    	http.Error(w,
    		fmt.Sprintf("ERROR: %v", err),
    		http.StatusInternalServerError)
    }
    
    // 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 action from the request, and call the corresponding
    	// function that handles that action.
    	action := request.QueryResult.Action
    	if fn, ok := handlers[action]; ok {
    		response, err = fn(r.Context(), request)
    	} else {
    		err = fmt.Errorf("Unknown action: %s", action)
    	}
    	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
    	}
    }
    
    

  8. 点击部署

  9. 等待状态指示器显示函数已成功部署。等待期间,请检查您刚刚部署的代码。

为代理配置 webhook

现在,Webhook 以服务的形式存在,您需要将此 Webhook 与您的代理相关联。此操作通过 fulfillment 完成。如需为代理启用和管理 fulfillment,请执行以下操作:

  1. 转到 Dialogflow ES 控制台
  2. 选择您刚刚创建的预构建代理。
  3. 选择左侧边栏菜单中的 Fulfillment
  4. 网路钩子字段切换为已启用
  5. 请提供您在上述步骤中复制的网址。 将其他所有字段留空。
  6. 点击页面底部的保存

启用 fulfillment 的屏幕截图。

现在已经为代理启用了 fulfillment,您需要为意图启用 fulfillment:

  1. 在左侧边栏菜单中选择意图 (Intents)。
  2. 选择 account.balance.check intent。
  3. 向下滚动到 Fulfillment 部分。
  4. 开启为此意图启用 webhook 调用
  5. 点击保存

试用代理

您现在可以试用代理了。 点击测试代理按钮以打开模拟器。 尝试与客服人员进行以下对话:

轮流对话 代理
1 您好 您好!感谢您选择惠家银行。
2 我想了解自己的账号余额 您希望将余额用于储蓄账户还是支票账户?
3 正在检查 您的最新余额为:$0.00

在第 3 轮对话时,您提供了“checking”作为帐号类型。account.balance.check intent 具有一个名为 account 的参数。在此对话中,此参数设置为“checking”。 该 intent 的操作值也为“account.balance.check”。系统将调用 webhook 服务,并向其传递参数和操作值。

如果您检查上面的 webhook 代码,会发现此操作触发一个类似的命名函数被调用。该函数会确定帐号余额。 该函数会检查特定环境变量是否设置了用于连接到数据库的信息。 如果未设置这些环境变量,则函数将使用硬编码的帐号余额。 在后续步骤中,您将更改函数的环境,使其从数据库中检索数据。

问题排查

网络钩子代码包含日志记录语句。如果您遇到问题,请尝试查看函数日志

更多信息

如需详细了解上述步骤,请参阅: