以Apps Script試驗LINE bot的flex message

關於LINE flex message官方介紹

會叫做flex message是因為其排版方式與網頁CSS的flex模式,主要是在手機/平板上呈現。在電腦版呈現時只會顯示 "本訊息無法顯示。 請至手機版LINE中查看。"

模擬器

如果是要設計Flex message可以用官方Line flex message模擬器(需登入LINE)

https://developers.line.biz/flex-simulator/

使用CURL嘗試官方範例

官方提供最簡單的測試就是使用推播訊息API,範例如下:

curl -v -X POST https://api.line.me/v2/bot/message/push \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer {你的LINE BOT TOKEN寫在這裡}' \
-d '{
"to": "Ua...使用者的ID...bf",
"messages": [
{
"type": "flex",
"altText": "This is a Flex Message",
"contents": {
"type": "bubble",
"body": {
"type": "box",
"layout": "horizontal",
"contents": [
{
"type": "text",
"text": "Hello,"
},
{
"type": "text",
"text": "World!"
}
]
}
}
}
]
}'



一般的LINE BOT訊息

/// 一般類型的BOT訊息
function doReply(replyToken, messages) {
if (!messages) return; // 索性就不回訊息了
const toLineMsg = m => {
if (typeof m === 'object') m = JSON.stringify(m);
if (typeof m !== 'string') m = '' + m;
return [{ type: 'text', text: m }];
};
UrlFetchApp.fetch('https://api.line.me/v2/bot/message/reply', {
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': `Bearer ${CHANNEL_ACCESS_TOKEN}`,
},
method: 'post',
payload: JSON.stringify({
replyToken,
messages: toLineMsg(messages),
}),
});
}


使用Flex的LINE BOT訊息

// flex類型(帶圖片跟排版)的BOT訊息
function doFlexReply(replyToken, flexMsg, alterMsg) {
if (typeof flexMsg === 'string') {
try {
flexMsg = JSON.parse(flexMsg);
} catch (e) {
return; // 索性就不回訊息了
}
}
if (typeof flexMsg === 'object') {
if (flexMsg.type !== 'bubble' && flexMsg.type !== 'carousel') {
return; // 索性就不回訊息了
}
}
const altText = typeof alterMsg === 'string' ? alterMsg : 'a flex message';
UrlFetchApp.fetch('https://api.line.me/v2/bot/message/reply', {
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': `Bearer ${CHANNEL_ACCESS_TOKEN}`,
},
method: 'post',
payload: JSON.stringify({
replyToken,
messages: [{ type: 'flex', altText, contents: flexMsg }],
}),
});
}


其他參考資料

https://developers.line.biz/en/docs/messaging-api/sending-messages/#methods-of-sending-message

留言