Example 5: How to render custom replies on different clients
Application developers often create custom H5 pages and cards for their clients. Examples of these cards include title text cards, image cards, and clickable cards. Each client can render these cards with a unique style. However, the data structure for the cards is always the same. For example, on a business client, the data format for a title text card is as follows:
Text card data format
{
"cardType": "TextCard",
"content": {
"title": "your title",
"text": "your text"
}
}
Typically, developers transform the data returned by a third-party API call into the required card data format. This allows them to generate cards dynamically. For example, in a weather query scenario, a developer can use the data from a real-time weather query to generate the data for a title card. The data for the generated card is as follows:
{
"cardType": "TextCard",
"content": {
"title": "2018-08-30",
"text": "Temperature is 28"
}
}
The first step is to build the conversation flow as shown in the following figure:
In this flow, the "Call Weather API" node is a function node that calls a third-party weather API. The "Dynamically Generate Card Data" node is a custom code function node. The third-party weather API returns data in the following format:
HTTP API response data format
{
"forecast": [
{
"date": "2018-08-30",
"temperature": "28"
},
{
"date": "2018-08-31",
"temperature": "30"
}
]
}
Sample code
In the "Dynamically Generate Card Data" function node, associate a Function Compute function. In the function's code, first deserialize the `lastOutputForFunction` field in `eventObj` into an object. Then, use the `date` and `temperature` fields from `forecast[0]` to construct the `card` object. Finally, serialize the `card` object into a string and assign it to the `htmlText` field of `overrideResponse`. After a value is assigned to the `htmlText` field, this value becomes the chatbot's final output for the current conversation turn.
Node.js
module.exports.handler = function(event, context, callback) {
/** event structure definition
For more details please VIEW DOCS HERE: https://lark.alipay.com/docs/share/1b48172d-0814-4a28-9ea0-3686a5bdb4a0
{
// read-only variables
"environment": "Object",
"lastOutputForFunction": "String",
"slotSummary": "Object",
// read/write variables
"global": "Object",
"outputForResponse": "Object",
"outputForFunction": "String",
"routeVariable": "String"
}
**/
try {
var eventObj = JSON.parse(event);
// // add your code here
var lastFunctionOutput = JSON.parse(eventObj.lastOutputForFunction);
var todayForecast = lastFunctionOutput.forecast[0];
var date = todayForecast.date;
var temp = todayForecast.temperature;
var card = {};
card["cardType"] = "TextCard";
card["content"] = {"title": date, "text":"Temperature is " + temp};
eventObj.overrideResponse.htmlText = [JSON.stringify(card)];
eventResult = JSON.stringify(eventObj);
callback(null, eventResult);
} catch (e) {
console.log(e);
eventResult = JSON.stringify(eventObj);
callback(null, eventResult);
//callback(null, e);
}
};
Python
# -*- coding: utf-8 -*-
import logging
import json
def handler(event, context):
logger = logging.getLogger()
logger.info(event)
eventObj = json.loads(event)
lastFunctionOutput = json.loads(eventObj['lastOutputForFunction'])
todayForecast = lastFunctionOutput['forecast'][0]
date = todayForecast['date']
temp = todayForecast['temperature']
card = {'cardType': 'TextCard'}
card['content'] = {'title': date, 'text': 'Temperature is ' + temp}
eventObj['overrideResponse'] = {'htmlText':[json.dumps(card)]}
return eventObj
Java
package com.aliyun.openservices.tcp.example.handler;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.fc.runtime.Context;
import com.aliyun.fc.runtime.PojoRequestHandler;
/**
* Created by weili on 2018/8/2.
*
* @author weili
* @date 2018/08/02
*/
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 lastFunctionOutput = JSON.parseObject(eventObj.getString("lastOutputForFunction"));
JSONObject todayForecast = lastFunctionOutput.getJSONArray("forecast").getJSONObject(0);
String date = todayForecast.getString("date");
String temp = todayForecast.getString("temperature");
JSONObject card = new JSONObject();
card.put("cardType", "TextCard");
JSONObject content = new JSONObject();
content.put("title", date);
content.put("text", "Temperature is " + temp);
card.put("content", content);
JSONArray htmlText = new JSONArray();
htmlText.add(card.toJSONString());
JSONObject overrideResponse = new JSONObject();
overrideResponse.put("htmlText", htmlText);
eventObj.put("overrideResponse", overrideResponse);
return eventObj;
}
}