Flex Messgeは以前
LINE BOTで「Flex Message」を使ってみる
でどのように表示できるか試してみました
今回は任意のタイミングでPUSHして
postbackを使ったコードを書きました
postbackを使うと何がいいか
- そのボタンを押した時に、そのボタンに設定したdataを返すことができる
ちなみに、ボタンテンプレートはスマホのみでしか表示できませんが、Flex MessageはMacでも表示されました
コード.gs
function get_token() {
return PropertiesService.getScriptProperties().getProperty('token');
}
function get_user_id() {
return PropertiesService.getScriptProperties().getProperty('user_id');
}
function doPost(e) {
var contents = e.postData.contents;
var obj = JSON.parse(contents);
var events = obj["events"];
for (var i = 0; i < events.length; i++) {
if (events[i].type == "postback") {
post_back(events[i]);
}
}
}
function flex_message() {
var postData = {
"to": get_user_id(),
"messages": [{
"type": "flex",
"altText": "this is a flex message",
"contents":
{
"type": "bubble",
"body": {
"type": "box",
"layout": "vertical",
"spacing": "md",
"contents": [
{
"type": "text",
"text": "Please select"
},
{
"type": "button",
"style": "primary",
"action": {
"type": "postback",
"label": "POSTBACK",
"data": "postback selected"
}
},
{
"type": "button",
"style": "primary",
"color": "#ffc0cb",
"action": {
"type": "uri",
"label": "URI",
"uri": "https://linecorp.com"
}
},
{
"type": "button",
"style": "secondary",
"action": {
"type": "message",
"label": "message",
"text": "text:message"
}
},
{
"type": "button",
"style": "primary",
"style": "secondary",
"color": "#7fffd4",
"action": {
"type": "datetimepicker",
"label": "datetimepicker",
"data": "datetimepicker selected",
"mode": "datetime",
"initial": "2018-12-29T00:00",
"max": "2019-10-15T23:59",
"min": "2018-12-29T00:00"
}
}
]
}
}
}]
};
var url = "https://api.line.me/v2/bot/message/push";
fetch_data(postData, url);
}
function post_back(e) {
var data = e.postback.data;
var replay_text = "";
if (data == "postback selected") {
replay_text = data;
} else if (data == "datetimepicker selected") {
replay_text = data + "\n" + e.postback.params['datetime'];
}
var postData = {
"replyToken": e.replyToken,
"messages": [{
"type": "text",
"text": replay_text + "\n" + JSON.stringify(e.postback)
}]
};
var url = "https://api.line.me/v2/bot/message/reply";
fetch_data(postData, url);
}
function fetch_data(postData, url) {
var options = {
"method": "post",
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer " + get_token()
},
"payload": JSON.stringify(postData)
};
UrlFetchApp.fetch(url, options);
}
|
関連記事
