ken_nogi/pleasanter/develop2/LINEWORKStoPLEASANTER/sample/sample.js
Kenichiro NOGI 88a402ce0f up
2026-07-10 18:13:30 +09:00

102 lines
3.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const ACCESS_TOKEN = 'あなたのLINE WORKS ボット用アクセストークン';
const TARGET_SERVER_URL = 'https://your-destination-server.com/api'; // 最終送信先
function doPost(e) {
const data = JSON.parse(e.postData.contents);
const event = data.events[0];
const userId = event.source.userId;
const userText = event.content ? event.content.text : "";
// ユーザーの状態を保存・取得するためのキー
const userProps = PropertiesService.getScriptProperties();
let step = userProps.getProperty(userId) || "0";
if (userText === "キャンセル") {
userProps.deleteProperty(userId);
sendMessage(userId, "アンケートを中断しました。");
return;
}
// ステップごとの分岐
switch (step) {
case "0": // 開始
sendMessage(userId, "アンケートを開始します。\nまずは【お名前】を入力してください。");
userProps.setProperty(userId, "1");
break;
case "1": // 名前を受け取った
userProps.setProperty(userId + "_name", userText);
sendMessage(userId, "次に【希望日】を 2026/03/01 の形式で入力してください。");
userProps.setProperty(userId, "2");
break;
case "2": // 日付を受け取った
userProps.setProperty(userId + "_date", userText);
// 選択肢Quick Replyを送る
sendQuickReply(userId, "今回の満足度を教えてください。", ["満足", "普通", "不満"]);
userProps.setProperty(userId, "3");
break;
case "3": // 選択肢を受け取った(最終ステップ)
const finalData = {
name: userProps.getProperty(userId + "_name"),
date: userProps.getProperty(userId + "_date"),
rating: userText,
userId: userId
};
// --- ここであなたのサーバーへ送信 ---
sendToExternalServer(finalData);
sendMessage(userId, "ご回答ありがとうございました!データを送信しました。");
// 状態をリセット(お掃除)
clearUserData(userId, userProps);
break;
}
}
// メッセージ送信用関数
function sendMessage(userId, text) {
UrlFetchApp.fetch(`https://www.worksapis.com/v1.0/bots/{botId}/users/${userId}/messages`, {
method: "post",
headers: { "Authorization": "Bearer " + ACCESS_TOKEN },
contentType: "application/json",
payload: JSON.stringify({ "content": { "type": "text", "text": text } })
});
}
// 選択肢ボタンQuick Reply送信用関数
function sendQuickReply(userId, text, options) {
const items = options.map(opt => ({
"action": { "type": "message", "label": opt, "text": opt }
}));
UrlFetchApp.fetch(`https://www.worksapis.com/v1.0/bots/{botId}/users/${userId}/messages`, {
method: "post",
headers: { "Authorization": "Bearer " + ACCESS_TOKEN },
contentType: "application/json",
payload: JSON.stringify({
"content": {
"type": "text",
"text": text,
"quickReply": { "items": items }
}
})
});
}
// 外部サーバー送信
function sendToExternalServer(data) {
UrlFetchApp.fetch(TARGET_SERVER_URL, {
method: "post",
contentType: "application/json",
payload: JSON.stringify(data)
});
}
function clearUserData(userId, props) {
props.deleteProperty(userId);
props.deleteProperty(userId + "_name");
props.deleteProperty(userId + "_date");
}