我从 wit.ai 收到一个 json 对象,其中包含一些快速回复元素,如下所示:
"msg": "So glad to have you back. What do you want me to do?
"action_id": "6fd7f2bd-db67-46d2-8742-ec160d9261c1",
"confidence": 0.08098269709064443,
"quickreplies": [
"News?",
"Subscribe?",
"Contribute?",
"Organize?"
],
"type": "msg"
然后,当它们传递到 Facebook Messenger 时,我需要将它们转换为稍微不同的格式,如下面的代码所述。 Wit 仅公开“消息”和“快速回复”。你能建议一个好方法来做到这一点吗?据我了解,它位于“console.log(element)”之后。
if (quickreplies){
// got simple array of quickreplies
// need to format quickreplies for FB:
// "quick_replies":[
// {
// "content_type":"text",
// "title":"Red",
// "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_RED"
// },
// {
// "content_type":"text",
// "title":"Green",
// "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_GREEN"
// }
console.log('we got quickreplies, here they are:');
var quick_replies = []; // ??
quickreplies.forEach(function(element) {
console.log(element)
});
}
else (console.log('no quickreplies'));
在上面的例子中,最终结果应该是这样的:
"recipient":{
"id":"USER_ID"
},
"message":{
"text":"Pick a color:",
"quick_replies":[
{
"content_type":"text",
"title":"Red",
"payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_RED"
},
{
"content_type":"text",
"title":"Green",
"payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_GREEN"
}
]
}
我不确定这是否是一个混乱的过程,但不存在“JSON 对象”这样的东西。一种方法是使用返回的数据对象JSON.parse
与处理任何其他对象的方式相同。当然,在发送到 FB 之前,必须使用以下方法将数据对象转换为 JSON 字符串格式JSON.stringify
. This might根据数据发送方式,某些代码库中会自动发生。
这是一个准备的例子quick-replies
array - 我只是为有效负载选择了一个示例结构并使用它。这quick_replies
array 仍然是一个对象,尚未转换为 JSON 字符串。
Edit仅文本有效负载的格式,如第一个所示仅文本示例,用于快速回复 https://developers.facebook.com/docs/messenger-platform/send-api-reference/quick-replies表示有效负载是一个字符串。下面的代码已更新以满足此要求。
// test values for quickreplies:
var quickreplies= [ "News?", "Subscribe?", "Contribute?", "Organize?" ];
/********
convert quickreplies to quick_replies array
using an example payload of:
{ "text" : "text string", // button text
"index" : index, // index into quickreply for button
"other": "tbd" // anything else needed in a reply
}
*********/
var quick_replies;
if (quickreplies) {
console.log('we got quickreplies, here they are:');
quick_replies = quickreplies.map( function(element, index) {
var payload = {
text: element,
index: index,
other: "tbd" // example value only.
};
var payloadString = JSON.stringify( payload);
console.log(element);
var quick_reply = {
content_type: "text",
title: element,
payload: payloadString
};
console.log("** converted to : " + JSON.stringify(quick_reply));
});
quickreplies=null; // housekeeping
}
else {
console.log('no quickreplies');
quick_replies = undefined; // or [] ?
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)