關於使用 SDK 開發自訂元件

技能中的每個狀態都使用系統元件或自訂元件。

系統元件內建於技能,且永遠可用。它們提供動作,例如輸出文字和設定變數。自訂元件提供商業系統 (例如資料庫和 CRM 系統) 的存取權。

To develop a complete custom component, you create an API in Oracle Mobile Hub and define its endpoints along with a backend, which controls access to the API.After the API and backend are defined, you create a connector in Oracle Mobile Hub.連線器的目的是將連線詳細資訊摘要至記錄系統,而不需要在實行中編碼連線詳細資訊。Finally, you write the API’s implementation and upload it to Oracle Mobile Hub.

建立自訂元件

Custom components are implemented as APIs that expose a GET method and a POST method.在設計階段,Skill Builder UI 會呼叫 GET 端點,以擷取 API 提供的服務清單。在程式實際執行時,技能會使用 POST 要求來存取 API 所提供的功能。
建立自訂元件是一個兩個步驟的處理作業。首先,定義端點,然後定義實行。定義端點時,您可以為端點指定名稱、HTTP 方法和其他參數。The implementation is the JavaScript that you write and upload to Oracle Mobile Hub.它會處理您為 API 定義的 GET 和 POST 方法。

定義 API 端點

You can host the API on any Node.js container, but it's best to use Oracle Mobile Hub for that.Oracle Mobile Hub allows you to use a connector, which provides a level of abstraction between the custom component API and external resources such as a database or other system of record.否則,您必須將連線資訊硬式編碼成 API 實行代碼。

若要定義自訂元件的端點:

  1. In the side menu, expand Development and click APIs.
  2. Click New API and select API.
  3. Enter a name and a short description for the API and click Create.
  4. When the API page opens, click Endpoints.
  5. Click New Resource.
  6. In the Resource Path field, enter components then click Methods.
  7. Click Add Method and select GET.
  8. When the page for the components endpoint opens, click Save.
  9. Go back to the Endpoints page and click the plus sign beside the components resource.A nested resource is added.
  10. In the Resource Path field for the new resource, enter {componentName} then click Methods.
  11. Select Required then click Add Method and select POST.
  12. Click Save.
完成之後,「端點」頁面的外觀應該與下列螢幕擷取類似:

Next, click Security and make sure that the Login Required switch is off.

建立並設定後端

後端的作用就像是機器人與其自訂元件之間的安全閘道,會以一或多個 Api 的方式實行。

建立後端之後,您需要將一或多個 Api 與其關聯。您可以透過後端存取關聯的 API,以提供 API 和處理認證的基礎 URL。

  1. In the side menu, expand Development and click Backends.
  2. Click New Backend.
  3. Enter a name and a description for the backend and click Create.
  4. After the backend is created, associate an API to the backend.
    1. In the side menu for the backend, click APIs.
    2. Click Select APIs.
      即會開啟「API 目錄」。
    3. Locate the API that you want to add and click the plus icon.

建立連線器

A connector provides a level of abstraction between the custom component API and resources external to Oracle Mobile Hub such as a database or other system of record. 雖然您可以直接從自訂元件連線至外部資源,但因為對外部資源的連線明細所做的變更不需要修訂您自訂元件程式碼的任何修訂版本,所以最好使用連線器。

在您開始之前,請收集下列資訊:

  1. 描述您所連線 API 的 Swagger 文件。如果您沒有 Swagger 文件,那麼您需要 API 的基本 URL。

  2. 您所連線之 API 的安全證明資料。連線器支援 OAUTH、基本認證、SAML 以及 JWT。

建立連線器:

  1. In the side menu, expand Development and click Connectors.
  2. Click New Connector and select REST.
  3. Enter a name and a description for the connector and click Create.The configurator opens to the General page.
  4. Click Descriptor and enter the location of the Swagger document.If you don't have a Swagger document, select I don't have a descriptor and enter the base URL of the API.
  5. Click Security and set the security policies for the connector.
  6. Click Test and test the connection to make sure that the connector is working.For example, if you are connecting to a database, make sure that you can send an SQL statement and get the result.
  7. When you are done testing, click Done.

撰寫自訂元件的實行代碼

定義 API 端點並設定後端之後,您就可以開發自訂元件的實行。

下列範例顯示自訂元件的內部結構,它為技能機器人提供訂單編號服務,而技能機器人則為銷售市場的公司提供線上訂單。

tshirtordertaker
\---tshirtordertaker
    |   package-lock.json
    |   package.json
    |   tshirtordertaker.js
    |
    +---components
    |       OrderNumber.js
    |
    +---lib
    |       config.js
    |       database.js

此範例顯示檔案結構的建議版面配置。The main field in package.json points to tshirtordertaker.js.Within tshirtordertaker.js, you initialize the component middleware, where you define the location of the file or files that implement the custom component.

The following sample shows what thsirtordertaker.js looks like.The location of the custom component implementation is defined in the register option, which in this case is the ./components directory.

/**
 * The ExpressJS namespace.
 * @external ExpressApplicationObject
 * @see {@link http://expressjs.com/3x/api.html#app}
 */

const OracleBot = require('@oracle/bots-node-sdk');

/**
 * Mobile Cloud custom code service entry point.
 * @param {external:ExpressApplicationObject} service 
 */
module.exports = function(service) {
    OracleBot.init(service, {
        logger: console
    });
    
    OracleBot.Middleware.customComponent(service, {
        cwd: __dirname,
        baseUrl: '/mobile/custom/TShirtOrderTaker/components',
        register: './components',
    });
};

The baseUrl value is in the form of /mobile/custom/<API-Name>/components where <API-Name> is the name that you gave the API when you created it in Oracle Mobile Hub.The register value is the directory that contains the file or files that implement the service.

In this case, the components directory has one file, called OrderNumber.js.This file contains the metadata and invoke functions that the bot system requires of every custom component.The following snippet shows what the beginning of OrderNumber.js looks like:

'use strict'

const { DBConnector } = require('../lib/database');
const { DB_CONNECTOR_NAME, DB_CONNECTOR_VERSION } = require('../lib/config');

/**
 * normalize color for db queries
 * @param {string} color 
 */

module.exports = {

    metadata: () => ({
        name: "OrderNumber",
        properties: { customerID: { type: "string", required: true } },
        supportedActions: [
            "instock",
            "backorder"
        ]
    }),

    invoke: (conversation, done) => {

        // deconstruct the conversation to get connectors instance
        const { oracleMobile } = conversation;
        
        if (!oracleMobile) {
            conversation.error(true);
            conversation.reply('The oracleMobile reference was not found. There might be a problem with this API');
            done();
        } else {
            // instantiate DBConnector helper class with backend connectors object
            const db = new DBConnector(oracleMobile.connectors, DB_CONNECTOR_NAME, DB_CONNECTOR_VERSION);
         .
         .
         .       

In this case, a connection to a database is made through a connector API in Oracle Mobile Hub.In the example structure shown earlier, the code for DBConnector would be implemented in database.js.您自己的導入程式碼將會不同,但結構應該相同。

上傳實行

您上傳的套裝程式稱為實行存檔,且包含在.zip 檔案中。

這裡所述上傳實行的處理作業是手動處理作業。不過,命令行選項是可用的。See the Oracle Mobile Hub documentation for instructions on how to download, set up, and use the Custom Code Test Tools that are on Oracle Technology Network (OTN).

  1. Zip the top-level directory to create an implementation archive.
  2. Upload the package to your API.
    1. Log into Oracle Mobile Hub and open your API.
    2. On the API page, click Implementation.
    3. Upload the API.You can click Upload an implementation archive or drag it onto the page.

測試實行

上傳實行之後,您應該進行測試。

  1. Click Test at the top of the page.
  2. Make sure that the GET /components endpoint is selected
  3. Select the appropriate Backend.
  4. Set the Authentication Method.
  5. Click Test Endpoint.

如果測試成功,您應該會見到 200 的回應狀態和 JSON 有效負載。有效負載應具有與下列 JSON 相同的結構:

{
    "version": "1.1",
    "components": [
        {
            "name": "OrderNumber",
            "properties": {
                "customerID": {
                    "type": "string",
                    "required": true
                }
            },
            "supportedActions": [
                "instock",
                "backorder"
            ]
        }
    ]
}

新增自訂元件至您的 Bot

在部署自訂元件並準備好進行作業之後,將其新增至技能機器人。

您必須先在技能機器人 UI 中設定元件服務,以新增自訂元件。接下來,您可以編輯 BotML 流程,以新增呼叫自訂元件的狀態以及處理回應的狀態。設定好所有項目之後,請測試機器人。

建立自訂元件的服務

若要設定服務,您需要提供代管自訂元件之服務的連線和認證資訊。

您需要代管自訂元件 API 的後端 ID,以及行動使用者的匿名金鑰或證明資料。您可以從建立的後端摘要頁面取得後端 ID 和匿名索引鍵,以代管 API。

您還需要服務用來擷取自訂元件之描述資料的 URL。You can form the metadata URL by copying the URL for the API from the General page of the API Designer and then appending /components to it.

  1. In the designer UI for your skill bot, open the components editor.
  2. Click + Service.
  3. Enter the connection and authentication information for the service that hosts your custom component.If you're using an Oracle Mobile Hub backend, make sure that you append the Metadata URL with /components.
  4. Click Create.

更新對話方塊流程

下列程序中的對話方塊流程專供雙工訂單接管員技能機器人使用。它使用稱為 OrderNumber 的自訂元件 (在稱為「取得訂單號碼」的狀態內)。當機器人進入此狀態時,系統會呼叫自訂元件實行。顯示的範例與接受 customerID 作為輸入的自訂元件對應。在此情況下,ID 會被編碼,但也可以傳入變數。自訂元件也能夠存取從使用者收集的技能機器人資訊,例如數量、大小及顏色。在使用"instock"或"Late"回應之前,自訂元件會設定稱為 orderNumber 的變數。

  1. In the designer UI for your skill bot, open the flow editor.
  2. Add the state that uses your custom component.
    Get Order Number:
        component: "OrderNumber"
        properties:
            customerID: "246810"
        transitions:
            actions:
                instock: "Done"
                backorder: "No Stock"
    
  3. Add the Done state.
    Done:
        component: "System.Output"
            properties:
                text: "Come down and pick up your order of ${quantity.value.number} ${color.value} ${size.value} size shirts. Your order number is ${orderNumber.value}"
            transitions:
                return: "Done"
    
  4. Add the No Stock state.
    No Stock:
        component: "System.Output"
            properties:
                text: "Sorry! We have no shirts of that type left, but they are on backorder. The backorder number is ${orderNumber.value}."
                keepTurn: true
        transitions:
            next: "Good Bye"