示例编写程序1 将对话参数传递至函数里

在电商领域,很多时候用户希望查询自己的订单情况,比如订单进度、是否发货等等,系统希望机器人能够通过对话的方式,来向用户收集订单信息,并且根据订单信息进行下一步的查询等操作。在这个例子中,对话流程中有一个叫做“查订单”的意图,包含一个叫做“orderId”的参数。在对话流设计中,设计填槽节点来让机器人通过对话的方式收集用户的订单号orderId。随即在函数节点中,想获取机器人收集到的orderId,利用它来做进一步操作,比如在这个例子中根据订单号的值来进行分支判断。如果订单号是以“A_”开头的话,那么属于A类订单,否则属于其他类订单。

代码示例

在这个例子中,首先获取到eventObj中的slotSummary字段,slotSummary字段中包含了所有对话中意图的参数,以Key-Value的形式存储,Key的组成为“意图名.参数名”。接下来程序通过判断查订单意图的orderId参数的值来做了一个分支判断。分支判断的具体应用在后面的例子中会涉及到。

Node.js

module.exports.handler = function(event, context, callback) {
    /** event structure definition
    {
      // read-only variables
      "environment": "Object",
      "lastOutputForFunction": "String",
      "slotSummary": "Object",

      // read/write variables
      "global": "Object",
      "overrideResponse": "Object",
      "functionOutput": "String",
      "routeVariable": "String"
    }
    **/
    var arr = "";
    var eventResult = "";
    try {
        var eventObj = JSON.parse(event);
        // add your code here
        var slots = eventObj["slotSummary"];
        var orderId = slots["查订单.orderId"];
        if (orderId.startsWith("A_")) {
            eventObj.routeVariable = '1';
        } else {
            eventObj.routeVariable = '0';
        }
        eventResult = JSON.stringify(eventObj);
        callback(null, eventResult);
    } catch (e) {
        eventResult = JSON.stringify(eventObj);
        callback(null, eventResult);
    }
};

Python

# -*- coding: utf-8 -*-
import logging  
import json

def handler(event, context):
  logger = logging.getLogger()
  logger.info(event)
  eventObj = json.loads(event)

  slots = eventObj["slotSummary"]
  logger.info(slots)
  orderId = slots[u"查订单.orderId"]

  if orderId.startswith("A_"):
    eventObj["routeVariable"] = "1"
  else:
    eventObj["routeVariable"] = "0"

  return eventObj

Java

package com.aliyun.openservices.tcp.example.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.PojoRequestHandler;

public class FunctionHandler implements PojoRequestHandler<JSONObject, JSONObject> {
    @Override
    public JSONObject handleRequest(JSONObject eventObj, Context context) {

        /**
         *  eventObj structure definition
         *
         *  read-only variables
         *  "environment": "Object",
         *  "lastOutputForFunction": "String",
         *  "slotSummary": "Object",
         *
         *  read/write variables
         *  "global": "Object",
         *  "overrideResponse": "Object",
         *  "functionOutput": "String",
         *  "routeVariable": "String"
         */

        JSONObject slots = eventObj.getJSONObject("slotSummary");
        String orderId = slots.getString("查订单.orderId");

        if (orderId.startsWith("A_")) {
            eventObj.put("routeVariable", "1");
        } else {
            eventObj.put("routeVariable", "0");
        }

        return eventObj;
    }
}