全部产品
阿里云办公

示例编写程序5 如何在不同的端上渲染自己想要的回复效果

更新时间:2018-09-27 13:52:00

场景描述

在很多会话端上,应用开发者会开发自己的H5页面,并创造一些个性化的卡片,比如标题文本卡片、图片卡片、点选卡片等,这些卡片可以在不同的会话端被渲染成不同的样式,但是数据存储的结构是相同的。例如,在某个业务的会话端中,标题文本卡片的数据格式如下:

文本卡片数据格式

  1. {
  2. "cardType": "TextCard",
  3. "content": {
  4. "title": "your title",
  5. "text": "your text"
  6. }
  7. }

一般情况下, 开发者希望将调用第三方接口返回的数据,通过格式转换,变成期待的卡片数据格式,以达到动态生成卡片的效果。例如,在查天气的例子当中,开发者希望根据实时查询到的天气结果,动态生成标题卡片数据,生成的卡片如下:

  1. {
  2. "cardType": "TextCard",
  3. "content": {
  4. "title": "2018-08-30",
  5. "text": "Temperature is 28"
  6. }
  7. }

那么我们首先构建对话流,如下图所示:

image.png | left | 747x352

其中“调用查天气API”节点为调用第三方查天气接口的函数节点,“动态生成卡片数据”节点为自定义代码函数节点。第三方查天气接口返回的数据格式如下:

HTTP接口返回数据格式

  1. {
  2. "forecast": [
  3. {
  4. "date": "2018-08-30",
  5. "temperature": "28"
  6. },
  7. {
  8. "date": "2018-08-31",
  9. "temperature": "30"
  10. }
  11. ]
  12. }

示例代码

在“动态生成卡片数据”函数节点中,我们关联到一个函数计算Function,在代码中,首先将eventObj中的lastOutputForFunction字段反序列化成Object,然后将它其中的forecast[0]的date和temperature字段用于构造卡片对象card,最后将card序列化成字符串格式赋值给overrideResponse的htmlText字段。overrideResponse的htmlText字段一旦被赋值后,机器人这轮对话最终的输出就将是这个值。

Node.js

  1. module.exports.handler = function(event, context, callback) {
  2. /** event structure definition
  3. For more details please VIEW DOCS HERE: https://lark.alipay.com/docs/share/1b48172d-0814-4a28-9ea0-3686a5bdb4a0
  4. {
  5. // read-only variables
  6. "environment": "Object",
  7. "lastOutputForFunction": "String",
  8. "slotSummary": "Object",
  9. // read/write variables
  10. "global": "Object",
  11. "outputForResponse": "Object",
  12. "outputForFunction": "String",
  13. "routeVariable": "String"
  14. }
  15. **/
  16. try {
  17. var eventObj = JSON.parse(event);
  18. // // add your code here
  19. var lastFunctionOutput = JSON.parse(eventObj.lastOutputForFunction);
  20. var todayForecast = lastFunctionOutput.forecast[0];
  21. var date = todayForecast.date;
  22. var temp = todayForecast.temperature;
  23. var card = {};
  24. card["cardType"] = "TextCard";
  25. card["content"] = {"title": date, "text":"Temperature is " + temp};
  26. eventObj.overrideResponse.htmlText = [JSON.stringify(card)];
  27. eventResult = JSON.stringify(eventObj);
  28. callback(null, eventResult);
  29. } catch (e) {
  30. console.log(e);
  31. eventResult = JSON.stringify(eventObj);
  32. callback(null, eventResult);
  33. //callback(null, e);
  34. }
  35. };

Python

  1. # -*- coding: utf-8 -*-
  2. import logging
  3. import json
  4. def handler(event, context):
  5. logger = logging.getLogger()
  6. logger.info(event)
  7. eventObj = json.loads(event)
  8. lastFunctionOutput = json.loads(eventObj['lastOutputForFunction'])
  9. todayForecast = lastFunctionOutput['forecast'][0]
  10. date = todayForecast['date']
  11. temp = todayForecast['temperature']
  12. card = {'cardType': 'TextCard'}
  13. card['content'] = {'title': date, 'text': 'Temperature is ' + temp}
  14. eventObj['overrideResponse'] = {'htmlText':[json.dumps(card)]}
  15. return eventObj

Java

  1. package com.aliyun.openservices.tcp.example.handler;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONObject;
  5. import com.aliyun.fc.runtime.Context;
  6. import com.aliyun.fc.runtime.PojoRequestHandler;
  7. /**
  8. * Created by weili on 2018/8/2.
  9. *
  10. * @author weili
  11. * @date 2018/08/02
  12. */
  13. public class FunctionHandler implements PojoRequestHandler<JSONObject, JSONObject> {
  14. @Override
  15. public JSONObject handleRequest(JSONObject eventObj, Context context) {
  16. /**
  17. * eventObj structure definition
  18. *
  19. * read-only variables
  20. * "environment": "Object",
  21. * "lastOutputForFunction": "String",
  22. * "slotSummary": "Object",
  23. *
  24. * read/write variables
  25. * "global": "Object",
  26. * "overrideResponse": "Object",
  27. * "functionOutput": "String",
  28. * "routeVariable": "String"
  29. */
  30. JSONObject lastFunctionOutput = JSON.parseObject(eventObj.getString("lastOutputForFunction"));
  31. JSONObject todayForecast = lastFunctionOutput.getJSONArray("forecast").getJSONObject(0);
  32. String date = todayForecast.getString("date");
  33. String temp = todayForecast.getString("temperature");
  34. JSONObject card = new JSONObject();
  35. card.put("cardType", "TextCard");
  36. JSONObject content = new JSONObject();
  37. content.put("title", date);
  38. content.put("text", "Temperature is " + temp);
  39. card.put("content", content);
  40. JSONArray htmlText = new JSONArray();
  41. htmlText.add(card.toJSONString());
  42. JSONObject overrideResponse = new JSONObject();
  43. overrideResponse.put("htmlText", htmlText);
  44. eventObj.put("overrideResponse", overrideResponse);
  45. return eventObj;
  46. }
  47. }