此 API 提供類似 NT Notify 的功能,允許應用程式向使用者發送通知。您需要生成 API Token 進行身份驗證。
端點: GET /api/status
描述: 查詢 API 服務狀態。
Authorization: Bearer YOUR_API_TOKEN
{
"status": 200,
"message": "服務運行中",
"data": {
"system_status": "normal",
"bot_status": "active",
"uptime": "99.9%",
"last_updated": "2023-10-15T12:34:56Z"
}
}
{
"status": 401,
"message": "無效的 Token"
}
| 參數名稱 | 類型 | 描述 |
|---|---|---|
| status | integer | HTTP 狀態碼 |
| message | string | 狀態訊息 |
| data.system_status | string | 系統狀態 (normal 或 unavailable) |
| data.bot_status | string | 機器人狀態 (active, deleted 或 not_found) |
| data.uptime | string | 系統運行時間百分比 |
| data.last_updated | string | 最後更新時間 (ISO 8601 格式) |
curl -X GET \
/api/status \
-H 'Authorization: Bearer YOUR_API_TOKEN'
<?php
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => '/api/status',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer YOUR_API_TOKEN',
],
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
fetch('/api/status', {
method: 'GET',
headers: {
'Authorization': 'Bearer YOUR_API_TOKEN'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
端點: POST /api/notify
描述: 發送通知訊息。
Authorization: Bearer YOUR_API_TOKEN
Content-Type: application/json
| 參數名稱 | 類型 | 必填 | 描述 |
|---|---|---|---|
| message | string | 是 | 要發送的訊息內容 (最多 5000 字元) |
| title | string | 否 | 訊息標題 (最多 255 字元) |
| image_url | string | 否 | 要附加的圖片 URL |
| recipient_id | string | 否 | 指定單一接收者的 LINE 用戶 ID |
| recipient_ids | array | 否 | 指定多個接收者的 LINE 用戶 ID 陣列,用於群發訊息 (最多 500 位) |
| send_to_all | boolean | 否 | 是否發送給所有會員 (廣播),設為 true 時需謹慎使用 |
| recipient_group_id | string | 否 | 指定單一接收群組的 LINE 群組 ID |
| recipient_group_ids | array 或 string | 否 | 指定多個接收群組的 LINE 群組 ID 陣列。也可以用逗號分隔的字串,例如: "id1,id2,id3" |
{
"success": true,
"message": "訊息已發送",
"data": {
"recipients_count": 1,
"sent_at": "2023-10-15T12:34:56Z"
}
}
{
"success": false,
"message": "驗證失敗",
"errors": {
"message": ["訊息內容不能為空"]
}
}
| 參數名稱 | 類型 | 描述 |
|---|---|---|
| success | boolean | 是否成功 (true: 成功, false: 失敗) |
| message | string | 狀態訊息 |
| data.recipients_count | integer | 接收訊息的用戶數量 (僅在成功時提供) |
| data.sent_at | string | 訊息發送時間 (ISO 8601 格式,僅在成功時提供) |
| errors | object | 驗證錯誤訊息 (僅在參數驗證失敗時提供) |
# 基本發送
curl -X POST \
/api/notify \
-H 'Authorization: Bearer YOUR_API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"message": "Hello World",
"title": "通知標題",
"image_url": "https://example.com/image.jpg"
}'
# 發送給特定用戶
curl -X POST \
/api/notify \
-H 'Authorization: Bearer YOUR_API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"message": "This is a personal message",
"title": "個人通知",
"recipient_id": "U4af4980629..."
}'
# 群發給多個用戶
curl -X POST \
/api/notify \
-H 'Authorization: Bearer YOUR_API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"message": "This is a group message",
"title": "群組通知",
"recipient_ids": ["U4af4980629...", "U8c6d6tx42b..."]
}'
# 廣播給所有用戶
curl -X POST \
/api/notify \
-H 'Authorization: Bearer YOUR_API_TOKEN' \
-H 'Content-Type: application/json' \
-d '{
"message": "This is a broadcast message",
"title": "廣播通知",
"send_to_all": true
}'
<?php
/**
* 發送簡單通知訊息
*/
function sendNotification($message, $title = null, $imageUrl = null) {
$apiUrl = 'https://notify.example.com/api/notify';
$apiToken = 'YOUR_API_TOKEN_HERE';
// 準備請求資料
$data = [
'message' => $message
];
// 如果有標題,加入 data
if (!empty($title)) {
$data['title'] = $title;
}
// 如果有圖片 URL,加入 data
if (!empty($imageUrl)) {
$data['image_url'] = $imageUrl;
}
// 初始化 cURL
$ch = curl_init($apiUrl);
// 設定 cURL 選項
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiToken
]);
// 執行 cURL 請求
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
/**
* 發送訊息給特定使用者
*/
function sendToUser($message, $recipientId, $title = null, $imageUrl = null) {
$apiUrl = 'https://notify.example.com/api/notify';
$apiToken = 'YOUR_API_TOKEN_HERE';
// 準備請求資料
$data = [
'message' => $message,
'recipient_id' => $recipientId
];
// 如果有標題,加入 data
if (!empty($title)) {
$data['title'] = $title;
}
// 如果有圖片 URL,加入 data
if (!empty($imageUrl)) {
$data['image_url'] = $imageUrl;
}
// 初始化 cURL
$ch = curl_init($apiUrl);
// 設定 cURL 選項
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiToken
]);
// 執行 cURL 請求
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
// 使用範例
// sendNotification('這是一條通知訊息', '測試標題');
// sendToUser('這是發送給特定用戶的訊息', 'U4af4980629...', '個人通知');
import requests
import json
# 設定 NT-Notify API 的 URL 和 API Token
API_URL = 'https://notify.example.com/api/notify'
API_TOKEN = 'YOUR_API_TOKEN_HERE' # 請將此替換為您的實際 API Token
def send_notification(message, title=None, image_url=None):
"""
發送簡單通知訊息
"""
# 準備請求資料
data = {'message': message}
# 如果有標題,加入 data
if title:
data['title'] = title
# 如果有圖片 URL,加入 data
if image_url:
data['image_url'] = image_url
# 設定請求標頭
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {API_TOKEN}'
}
# 發送 API 請求
response = requests.post(API_URL, headers=headers, json=data)
return response.json()
def send_to_user(message, recipient_id, title=None, image_url=None):
"""
發送訊息給特定使用者
"""
# 準備請求資料
data = {
'message': message,
'recipient_id': recipient_id
}
# 如果有標題,加入 data
if title:
data['title'] = title
# 如果有圖片 URL,加入 data
if image_url:
data['image_url'] = image_url
# 設定請求標頭
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {API_TOKEN}'
}
# 發送 API 請求
response = requests.post(API_URL, headers=headers, json=data)
return response.json()
# 使用範例
# result = send_notification("這是一條測試訊息", "測試標題")
# print(result)
// 設定 API 相關常數
const API_URL = '/api/notify';
const API_TOKEN = 'YOUR_API_TOKEN';
/**
* 發送基本通知
*/
async function sendNotification(message, title, imageUrl) {
// 準備請求資料
const data = { message };
// 如果有標題,加入 data
if (title) {
data.title = title;
}
// 如果有圖片 URL,加入 data
if (imageUrl) {
data.image_url = imageUrl;
}
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_TOKEN}`
},
body: JSON.stringify(data)
});
return await response.json();
} catch (error) {
console.error('Error:', error);
return { success: false, message: error.message };
}
}
/**
* 發送訊息給特定用戶
*/
async function sendToUser(message, recipientId, title, imageUrl) {
// 準備請求資料
const data = {
message,
recipient_id: recipientId
};
// 如果有標題,加入 data
if (title) {
data.title = title;
}
// 如果有圖片 URL,加入 data
if (imageUrl) {
data.image_url = imageUrl;
}
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_TOKEN}`
},
body: JSON.stringify(data)
});
return await response.json();
} catch (error) {
console.error('Error:', error);
return { success: false, message: error.message };
}
}
// 使用範例
// sendNotification('Hello World', '通知標題', 'https://example.com/image.jpg')
// .then(data => console.log(data));
// 設定 NT-Notify API 的 URL 和 API Token
var API_URL = 'https://notify.example.com/api/notify';
var API_TOKEN = 'YOUR_API_TOKEN_HERE'; // 請將此替換為您的實際 API Token
/**
* 發送單一訊息通知
*/
function sendNotification(message, title, imageUrl) {
// 準備請求資料
var payload = {
'message': message
};
// 如果有標題,加入 payload
if (title && title.trim() !== '') {
payload.title = title;
}
// 如果有圖片 URL,加入 payload
if (imageUrl && imageUrl.trim() !== '') {
payload.image_url = imageUrl;
}
// 設定 API 請求選項
var options = {
'method': 'post',
'contentType': 'application/json',
'headers': {
'Authorization': 'Bearer ' + API_TOKEN
},
'payload': JSON.stringify(payload),
'muteHttpExceptions': true
};
// 發送 API 請求
var response = UrlFetchApp.fetch(API_URL, options);
// 解析 API 回應
var result = JSON.parse(response.getContentText());
// 記錄結果
Logger.log('發送結果: ' + result.message);
return result;
}
/**
* 發送訊息給特定使用者
*/
function sendToUser(message, recipientId, title, imageUrl) {
// 準備請求資料
var payload = {
'message': message,
'recipient_id': recipientId
};
// 如果有標題,加入 payload
if (title && title.trim() !== '') {
payload.title = title;
}
// 如果有圖片 URL,加入 payload
if (imageUrl && imageUrl.trim() !== '') {
payload.image_url = imageUrl;
}
// 設定 API 請求選項
var options = {
'method': 'post',
'contentType': 'application/json',
'headers': {
'Authorization': 'Bearer ' + API_TOKEN
},
'payload': JSON.stringify(payload),
'muteHttpExceptions': true
};
// 發送 API 請求
var response = UrlFetchApp.fetch(API_URL, options);
return JSON.parse(response.getContentText());
}
/**
* 發送訊息給特定群組
*/
function sendToSpecificGroup() {
sendWebhook('這是發送給特定群組的訊息', {
'recipient_group_id': 'C4af4980629...'
});
}
/**
* 群發訊息給多個群組
*/
function sendToMultipleGroups() {
sendWebhook('這是群發給多個群組的訊息', {
'recipient_group_ids': ['C4af4980629...', 'C8c6d6tx42b...']
});
}
// 使用範例
// function testNotify() {
// sendNotification('這是一條通知訊息', '測試標題');
// }
您可以下載以下完整的範例程式碼:
本系統提供 API 查詢 LINE Bot 收到的訊息紀錄,支援多種篩選條件。需使用 JWT Token 驗證(先呼叫 POST /api/auth/login 取得)。
端點: GET /api/bots/{id}/messages
描述: 查詢指定 Bot 接收到的 LINE 訊息,支援多條件篩選。
Authorization: Bearer YOUR_JWT_TOKEN
| 參數名稱 | 類型 | 必填 | 描述 |
|---|---|---|---|
| line_user_id | string | 否 | 篩選特定 LINE 用戶發送的訊息 |
| line_group_id | string | 否 | 篩選特定 LINE 群組的訊息 |
| source_type | string | 否 | 篩選來源類型:user(個人訊息)或 group(群組訊息) |
| message_type | string | 否 | 篩選訊息類型:text、image、sticker 等 |
| start_date | string | 否 | 起始日期,格式 Y-m-d(例如 2024-01-01) |
| end_date | string | 否 | 結束日期,格式 Y-m-d(例如 2024-12-31) |
| per_page | integer | 否 | 每頁筆數(預設 15,最大 100) |
{
"status": 200,
"message": "取得接收訊息成功",
"data": {
"current_page": 1,
"total": 50,
"per_page": 15,
"data": [
{
"id": 1,
"user_bot_id": 1,
"line_user_id": "U4af4980629...",
"line_group_id": null,
"message_id": "123456789",
"message_type": "text",
"content": "Hello!",
"source_type": "user",
"created_at": "2024-01-01T12:00:00Z"
}
]
}
}
# 取得 Bot 所有接收訊息
curl -X GET "http://YOUR_DOMAIN/api/bots/1/messages" \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
# 只查詢個人訊息
curl -X GET "http://YOUR_DOMAIN/api/bots/1/messages?source_type=user" \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
# 查詢特定日期範圍的文字訊息
curl -X GET "http://YOUR_DOMAIN/api/bots/1/messages?message_type=text&start_date=2024-01-01&end_date=2024-01-31" \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
<?php
$botId = 1;
$apiUrl = "https://YOUR_DOMAIN/api/bots/{$botId}/messages";
$jwtToken = 'YOUR_JWT_TOKEN';
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl . '?source_type=user&per_page=20',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer {$jwtToken}",
],
]);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
foreach ($response['data']['data'] as $msg) {
echo "[{$msg['created_at']}] {$msg['source_type']}: {$msg['content']}" . PHP_EOL;
}
const botId = 1;
const jwtToken = 'YOUR_JWT_TOKEN';
async function getBotMessages(filters = {}) {
const params = new URLSearchParams(filters).toString();
const url = `/api/bots/${botId}/messages?${params}`;
const res = await fetch(url, {
headers: { 'Authorization': `Bearer ${jwtToken}` }
});
return await res.json();
}
// 查詢群組訊息
getBotMessages({ source_type: 'group', per_page: 10 })
.then(data => console.log(data));
端點: GET /api/messages
描述: 查詢目前登入使用者旗下「所有 Bot」接收到的訊息,可加上 bot_id 參數縮小範圍,適合跨 Bot 統一查詢。
Authorization: Bearer YOUR_JWT_TOKEN
| 參數名稱 | 類型 | 必填 | 描述 |
|---|---|---|---|
| bot_id | integer | 否 | 篩選特定 Bot(不填則查詢所有 Bot) |
| line_user_id | string | 否 | 篩選特定 LINE 用戶 |
| line_group_id | string | 否 | 篩選特定 LINE 群組 |
| source_type | string | 否 | user 或 group |
| message_type | string | 否 | 訊息類型:text、image、sticker 等 |
| start_date | string | 否 | 起始日期,格式 Y-m-d |
| end_date | string | 否 | 結束日期,格式 Y-m-d |
| per_page | integer | 否 | 每頁筆數(預設 15,最大 100) |
# 查詢所有 Bot 的接收訊息
curl -X GET "http://YOUR_DOMAIN/api/messages?per_page=20" \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
# 篩選某日期範圍內的群組訊息
curl -X GET "http://YOUR_DOMAIN/api/messages?source_type=group&start_date=2024-01-01&end_date=2024-01-31" \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
# 特定 Bot + 特定用戶
curl -X GET "http://YOUR_DOMAIN/api/messages?bot_id=1&line_user_id=U4af4980629..." \
-H "Authorization: Bearer YOUR_JWT_TOKEN"
<?php
$apiUrl = 'https://YOUR_DOMAIN/api/messages';
$jwtToken = 'YOUR_JWT_TOKEN';
$params = http_build_query([
'source_type' => 'user',
'start_date' => '2024-01-01',
'end_date' => '2024-01-31',
'per_page' => 20,
]);
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl . '?' . $params,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["Authorization: Bearer {$jwtToken}"],
]);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
echo "共 " . $response['data']['total'] . " 則訊息\n";
foreach ($response['data']['data'] as $msg) {
echo "[{$msg['created_at']}] {$msg['content']}\n";
}
const jwtToken = 'YOUR_JWT_TOKEN';
async function getAllMessages(filters = {}) {
const params = new URLSearchParams(filters).toString();
const res = await fetch(`/api/messages?${params}`, {
headers: { 'Authorization': `Bearer ${jwtToken}` }
});
return await res.json();
}
// 查詢所有 Bot 今日的個人訊息
const today = new Date().toISOString().split('T')[0];
getAllMessages({ source_type: 'user', start_date: today })
.then(data => {
console.log(`共 ${data.data.total} 則訊息`);
data.data.data.forEach(msg => {
console.log(`[${msg.created_at}] ${msg.content}`);
});
});
本系統提供 Webhook URL,您可以通過 HTTP 請求直接發送訊息而無需使用 API Token。
端點: POST 您的 Webhook URL
描述: 使用 Webhook URL 直接發送通知訊息。
獲取方式: 在 Bot 管理頁面中可以看到每個 Bot 生成的唯一 Webhook URL。
| 參數名稱 | 類型 | 必填 | 描述 |
|---|---|---|---|
| message | string | 是 | 要發送的訊息內容(最多 5000 字元) |
| title | string | 否 | 訊息標題(最多 255 字元),會顯示在訊息開頭 |
| image_url | string | 否 | 要附加的圖片 URL(必須是公開可訪問的圖片) |
| recipient_id | string | 否 | 指定單一接收者的 LINE 用戶 ID |
| recipient_ids | array 或 string | 否 | 指定多個接收者的 LINE 用戶 ID 陣列,最多 500 個。也可以用逗號分隔的字串,例如: "id1,id2,id3" |
| send_to_all | boolean | 否 | 是否發送給所有會員(廣播,需謹慎使用) |
| recipient_group_id | string | 否 | 指定單一接收群組的 LINE 群組 ID |
| recipient_group_ids | array 或 string | 否 | 指定多個接收群組的 LINE 群組 ID 陣列。也可以用逗號分隔的字串,例如: "id1,id2,id3" |
{
"status": "success",
"message": "訊息發送成功",
"data": {
"recipients_count": 1,
"sent_at": "2023-12-31T12:34:56"
}
}
{
"status": "error",
"message": "錯誤訊息",
"errors": {
"message": ["訊息內容不能為空"]
}
}
# 基本用法
curl -X POST \
"YOUR_WEBHOOK_URL" \
-H 'Content-Type: application/json' \
-d '{"message":"Hello World"}'
# 添加標題和圖片
curl -X POST \
"YOUR_WEBHOOK_URL" \
-H 'Content-Type: application/json' \
-d '{
"message":"這是訊息內容",
"title":"訊息標題",
"image_url":"https://example.com/image.jpg"
}'
# 發送給特定用戶
curl -X POST \
"YOUR_WEBHOOK_URL" \
-H 'Content-Type: application/json' \
-d '{
"message":"這是發送給特定用戶的訊息",
"recipient_id":"U4af4980629..."
}'
# 群發給多個用戶
curl -X POST \
"YOUR_WEBHOOK_URL" \
-H 'Content-Type: application/json' \
-d '{
"message":"這是群發訊息",
"recipient_ids":["U4af4980629...", "U8c6d6tx42b..."]
}'
# 發送給特定群組
curl -X POST \
"YOUR_WEBHOOK_URL" \
-H 'Content-Type: application/json' \
-d '{
"message":"這是發送給特定群組的訊息",
"recipient_group_id":"C4af4980629..."
}'
# 群發給多個群組
curl -X POST \
"YOUR_WEBHOOK_URL" \
-H 'Content-Type: application/json' \
-d '{
"message":"這是群發給多個群組的訊息",
"recipient_group_ids":["C4af4980629...", "C8c6d6tx42b..."]
}'
<?php
$webhookUrl = 'YOUR_WEBHOOK_URL';
// 基本用法
function sendWebhook($message, $extraParams = []) {
global $webhookUrl;
// 準備請求資料
$data = array_merge(['message' => $message], $extraParams);
// 初始化 cURL
$ch = curl_init($webhookUrl);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($data),
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
]);
// 執行請求
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return [
'code' => $statusCode,
'response' => json_decode($response, true)
];
}
// 發送基本訊息
$result = sendWebhook('Hello World');
// 添加標題和圖片
$result = sendWebhook('這是訊息內容', [
'title' => '訊息標題',
'image_url' => 'https://example.com/image.jpg'
]);
// 發送給特定用戶
$result = sendWebhook('這是發送給特定用戶的訊息', [
'recipient_id' => 'U4af4980629...'
]);
// 群發給多個用戶
$result = sendWebhook('這是群發訊息', [
'recipient_ids' => ['U4af4980629...', 'U8c6d6tx42b...']
]);
// 發送給特定群組
$result = sendWebhook('這是發送給特定群組的訊息', [
'recipient_group_id' => 'C4af4980629...'
]);
// 群發給多個群組
$result = sendWebhook('這是群發給多個群組的訊息', [
'recipient_group_ids' => ['C4af4980629...', 'C8c6d6tx42b...']
]);
const webhookUrl = 'YOUR_WEBHOOK_URL';
// 基本發送函數
async function sendWebhook(message, extraParams = {}) {
try {
const response = await fetch(webhookUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message,
...extraParams
})
});
return await response.json();
} catch (error) {
console.error('Error:', error);
return { status: 'error', message: error.message };
}
}
// 基本用法
sendWebhook('Hello World')
.then(result => console.log(result));
// 添加標題和圖片
sendWebhook('這是訊息內容', {
title: '訊息標題',
image_url: 'https://example.com/image.jpg'
}).then(result => console.log(result));
// 發送給特定用戶
sendWebhook('這是發送給特定用戶的訊息', {
recipient_id: 'U4af4980629...'
}).then(result => console.log(result));
// 群發給多個用戶
sendWebhook('這是群發訊息', {
recipient_ids: ['U4af4980629...', 'U8c6d6tx42b...']
}).then(result => console.log(result));
// 發送給特定群組
sendWebhook('這是發送給特定群組的訊息', {
recipient_group_id: 'C4af4980629...'
}).then(result => console.log(result));
// 群發給多個群組
sendWebhook('這是群發給多個群組的訊息', {
recipient_group_ids: ['C4af4980629...', 'C8c6d6tx42b...']
}).then(result => console.log(result));
// Google Apps Script 範例
// 設定 Webhook URL
var WEBHOOK_URL = 'YOUR_WEBHOOK_URL';
/**
* 基本發送函數
*
* @param {string} message 訊息內容
* @param {object} extraParams 額外參數
* @return {object} API 回應
*/
function sendWebhook(message, extraParams) {
// 準備請求資料
var payload = {
'message': message
};
// 合併額外參數
if (extraParams) {
for (var key in extraParams) {
payload[key] = extraParams[key];
}
}
// 設定 API 請求選項
var options = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payload),
'muteHttpExceptions': true
};
// 發送 API 請求
var response = UrlFetchApp.fetch(WEBHOOK_URL, options);
// 解析 API 回應
var result = JSON.parse(response.getContentText());
// 記錄結果
Logger.log('發送結果: ' + result.message);
return result;
}
/**
* 發送基本訊息
*/
function sendBasicMessage() {
sendWebhook('Hello World');
}
/**
* 發送帶標題和圖片的訊息
*/
function sendRichMessage() {
sendWebhook('這是訊息內容', {
'title': '訊息標題',
'image_url': 'https://example.com/image.jpg'
});
}
/**
* 發送訊息給特定用戶
*/
function sendToSpecificUser() {
sendWebhook('這是發送給特定用戶的訊息', {
'recipient_id': 'U4af4980629...'
});
}
/**
* 群發訊息給多個用戶
*/
function sendToMultipleUsers() {
sendWebhook('這是群發訊息', {
'recipient_ids': ['U4af4980629...', 'U8c6d6tx42b...']
});
}
/**
* 發送訊息給特定群組
*/
function sendToSpecificGroup() {
sendWebhook('這是發送給特定群組的訊息', {
'recipient_group_id': 'C4af4980629...'
});
}
/**
* 群發訊息給多個群組
*/
function sendToMultipleGroups() {
sendWebhook('這是群發給多個群組的訊息', {
'recipient_group_ids': ['C4af4980629...', 'C8c6d6tx42b...']
});
}
/**
* 與 Google Sheet 整合範例
* 根據試算表內容發送訊息
*/
function sendMessagesFromSheet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var dataRange = sheet.getRange("A2:C" + sheet.getLastRow());
var data = dataRange.getValues();
for (var i = 0; i < data.length; i++) {
var row = data[i];
var message = row[0]; // A列:訊息內容
var userId = row[1]; // B列:LINE用戶ID
var isSent = row[2]; // C列:是否已發送
// 如果尚未發送
if (!isSent) {
// 發送訊息
var result = sendWebhook(message, {
'recipient_id': userId
});
// 如果發送成功,標記為已發送
if (result.status === 'success') {
sheet.getRange(i + 2, 3).setValue(true);
}
}
}
}