在
[Line] Flex Message - 模擬器 取得 Flex Message json 內容搭配
[GAS] LineBot 傳送訊息,使用 push API 主動發出 Flex Message 發給使用者
function testSendFlexMessageFromGAS() {
const userId = getUserID();
const card = SendFlexMessageFromGAS();
pushFlexMessage(userId, 'altText:Hello Flex Message From GAS', card);
}
function SendFlexMessageFromGAS() {
return {
"type": "bubble",
"body": {
"type": "box",
"layout": "vertical",
"contents": [
{
"type": "text",
"text": "Flex Message Sample",
"weight": "bold",
"color": "#1DB446",
"size": "xs"
},
{
"type": "text",
"text": "Hello Flex Message",
"weight": "bold",
"size": "xl",
"color": "#1E293B"
},
{
"type": "text",
"text": "從 Google Apps Script 發出的第一張 Flex Message,這張卡片只用了最基礎的 body 區塊與 vertical 垂直排列容器",
"size": "sm",
"color": "#64748B",
"wrap": true,
"lineSpacing": "4px"
}
]
}
}
}
function pushFlexMessage(to, altText, flexContents) {
const channelAccessToken = getchannelAccessToken();
const payload = {
to,
messages: [
{
type: 'flex',
altText,
contents: flexContents
}
]
};
const options = {
method: 'post',
contentType: 'application/json',
headers: {
Authorization: `Bearer ${channelAccessToken}`
},
payload: JSON.stringify(payload),
muteHttpExceptions: true
};
const lineUrl = "https://api.line.me/v2/bot/message/push";
const response = UrlFetchApp.fetch(lineUrl, options);
const statusCode = response.getResponseCode();
const responseText = response.getContentText();
if (statusCode === 200) {
Logger.log(`Flex Message 推播成功!"${altText}"`);
return JSON.parse(responseText || '{}');
}
throw new Error(`LINE Push API 發送失敗 (HTTP ${statusCode}):${responseText}`);
}
function getchannelAccessToken() {
const scriptProperties = PropertiesService.getScriptProperties();
const rawToken = scriptProperties.getProperty('CHANNEL_ACCESS_TOKEN') || '';
// 自動去除前後空白、換行或誤加的雙引號/單引號
const channelAccessToken = rawToken.trim().replace(/^["']+|["']+$/g, '');
if (!channelAccessToken) {
throw new Error(
'尚未設定指令碼屬性 (Script Properties) 內的 CHANNEL_ACCESS_TOKEN'
);
}
return channelAccessToken;
}
function getUserID() {
const scriptProperties = PropertiesService.getScriptProperties();
const rawUserId = scriptProperties.getProperty('USER_ID') || '';
// 自動去除前後空白、換行或誤加的雙引號/單引號
const userId = rawUserId.trim().replace(/^["']+|["']+$/g, '');
if (!userId) {
throw new Error(
'尚未設定指令碼屬性 (Script Properties) 內的 USER_ID'
);
}
return userId;
}
payload 內的 Message 有兩個重點
- type 要指定為 flex
- altText 即為通知訊息,故意在文字前面打個 altText 來辨識
Flex Message josn 有修改部分文字,方便辨識是從 GAS 發出