Dialogflow client 端應用-以Go語言為例

有時候我們會有需要使用client來直接使用Dialogflow,底下就以Go為範例,來做一些示範。

環境準備

  • 建立專案並取得projectID
  • 啟動Dialogflow API
  • 設定認證
    • In the Cloud Console, go to the Create service account key page.
    • From the Service account list, select New service account.
    • In the Service account name field, enter a name.
    • From the Role list, select Project > Owner.
    • Click Create. A JSON file that contains your key downloads to your computer.
    • 將下載的json檔上傳到server主機上
  • 使用環境變數:export GOOGLE_APPLICATION_CREDENTIALS=”[PATH]”
  • 安裝需要的SDK
  • 安裝Go 函數
go get cloud.google.com/go/dialogflow/apiv2

撰寫程式

撰寫程式前,除了設定好上述認證檔的環境變數外,需要先準備好下列幾個變數:

  • Project ID: Use the project ID for the project you created in the setup steps.
  • Session ID: 應用程式自己取,如:”123456789″
  • Language code: 如:zh-TW、en-US(完整代碼參考

完整範例

package main

import(
   "fmt"
   "context"
   dialogflow "cloud.google.com/go/dialogflow/apiv2"
   dialogflowpb "google.golang.org/genproto/googleapis/cloud/dialogflow/v2"
)

func DetectIntentText(projectID, sessionID, text, languageCode string) (string, error) {
   ctx := context.Background()

   sessionClient, err := dialogflow.NewSessionsClient(ctx)
   if err != nil {
      return "", err
   }
   defer sessionClient.Close()

   if projectID == "" || sessionID == "" {
      return "", errors.New(fmt.Sprintf("Received empty project (%s) or session (%s)", projectID, sessionID))
   }

   sessionPath := fmt.Sprintf("projects/%s/agent/sessions/%s", projectID, sessionID)
   textInput := dialogflowpb.TextInput{Text: text, LanguageCode: languageCode}
   queryTextInput := dialogflowpb.QueryInput_Text{Text: &textInput}
   queryInput := dialogflowpb.QueryInput{Input: &queryTextInput}
   request := dialogflowpb.DetectIntentRequest{Session: sessionPath, QueryInput: &queryInput}

   response, err := sessionClient.DetectIntent(ctx, &request)
   if err != nil {
      return "", err
   }

   queryResult := response.GetQueryResult()
   fulfillmentText := queryResult.GetFulfillmentText()
   return fulfillmentText, nil
}

func main() {
   projectID := "ascare-eolcxp"
   sessionID := "123456789"
   query := "目前有那些任務"
   languageCode := "zh-TW"

   response, err := DetectIntentText(projectID, sessionID, query, languageCode)
   if err != nil {
      fmt.Println(err.Error())
      return
   }
   fmt.Printf("Output: %v\n", response)
}

參考文件