🥋

Geminiで自然言語を解釈する定期リマインダーSlack BOT「報衛門」のGAS

に公開

表題の通り,Gemini APIを通じて自然言語を解釈して制御する定期リマインダーSlack BOTである「報衛門(しらせもん,SHIRASEMON)」をGoogle Apps Scriptで書きました.

要件

必須要件

  • 終了指示を受けるまで定期的にリマインダーを送り続ける
  • リマインダー開始,終了の処理を自然言語で受け取る
  • 開始時,以下の項目を自然言語で受け取る
    • リマインダー間隔
    • リマインダー内容 (任意)
    • リマインダー開始日時 (任意)
  • 同時にメンションする人を設定可能
  • 完了時等,過去のリマインドメッセージを自動削除する

おまけ要件

  • リマインド中の項目一覧を人間が見れる
  • なんとなく古風な口調
  • 放置によりbotの口調とアイコンが変化する
リマインダー開始の例 リマインド中の報衛門(24~26回目)
リマインダー終了の例 "おもいつき @SHIRASEMONの薄い本" 報衛門が愛されている様子

ミソ

  • Gemini API(Gemma 3)でテキストからリマインドについての情報を抽出
    • Gemma 3にしている理由はレート制限がゆるいから
  • スプレッドシートをデータベースとして利用
  • アプリ名を「SHIRASEMON」にし,投稿時の表示名を「報衛門」とすることにより,メンションをしやすくした
  • Slackからのリトライリクエストを CacheService で弾き,二重処理を防止

流れ

  • receiver.gs
    メンション時のpostリクエストを受け取って動くファイル
    • CacheServiceに登録し,二重処理を防止
    • Gemini APIにより意図を分類する
      • SET_REMINDER と STOP_REMINDER と OTHER
    • SET_REMINDERの場合
      • Gemini APIにより,リマインダー要項を抽出する
      • メッセージ情報やリマインダー要項をスプレッドシートに登録する
      • 受け付けた旨をSlackに投稿する
    • STOP_REMINDERの場合
      • 終了した旨をスプレッドシートに登録する
      • 終了した旨をSlackに投稿する
      • 投稿されたリマインダーを削除する
  • sender.gs
    1分毎のトリガーを受け取って動くファイル
    • スプレッドシートからリマインド予定時刻が過ぎたレコードを探す
    • 当該スレッドにリマインドメッセージを送る
作るのをあきらめたmermaid

プログラム

script propertyに GEMINI_API_KEY と SLACK_BOT_TOKEN , SPREADSHEET_IDを入れます.
slack botのscopeに app_mention:read と channels:history,channels:read,chat:write , chat:write:customize,chat:write:public , groups:history, im:history ,im:read ,user:read を入れます.いらないのもある気がする...
slack botのEvent Subscriptionsにapp_mentionを入れます.
スプレッドシートは左から,投稿日時(UNIX),投稿日時,対応状況,投稿者ID,投稿者名,随伴者ID,随伴者名,メッセージ,チャンネルID,チャンネル名,スレッドID,投稿リンク,リマインド間隔,次のリマインド時間,リマインド回数,リマインドメッセージです.

receiver.gs
/**
 * SlackからのPOSTリクエ ストを受け取り、イベントの種類に応じて処理を行います。
 * @param {object} e HTTP POSTイベントオブジェクト
 * @return {object} Slackへの応答(TextOutput)
 */
function doPost(e) {
  const contents = JSON.parse(e.postData.contents);

  // 初回認証(URL Verification)の場合
  if (contents.type === 'url_verification') {
    return ContentService.createTextOutput(contents.challenge).setMimeType(ContentService.MimeType.TEXT);
  }

  // イベント(Event Callback)の場合
  if (contents.type === 'event_callback') {
    const event = contents.event;

    // 重複実行防止(10分間キャッシュ)
    if (isProcessed(event.event_ts)) {
      return ContentService.createTextOutput();
    }

    // BOTへのメンションの場合
    if (event.type === 'app_mention') {

      // テキストに含まれる直接のコマンドを優先処理
      if (event.text.includes('erase')) {
        cleanUpThread(event);
        return ContentService.createTextOutput();
      }

      // Geminiでユーザーの意図を分類
      const intentResult = classifyIntent(event);
      console.log('Intent Classified:', JSON.stringify(intentResult));

      switch (intentResult.intent) {
        case 'SET_REMINDER':
          registerNewReminder(event);
          break;
        case 'STOP_REMINDER':
          checkForCompletion(event);
          cleanUpThread(event);
          break;
        case 'OTHER':
        default:
          postConfirmationReply(event, 'ご下命の意図を測りかねます。');
          break;
      }
    }
  }

  // 常に空の応答を返し、Slackに正常受信を伝える
  return ContentService.createTextOutput();
}


/**
 * Gemini(AI)を使用してユーザーのメッセージ意図を分類します。
 * @param {object} event Slackのイベントオブジェクト
 * @return {object} 分類結果 { intent: 'SET_REMINDER' | 'STOP_REMINDER' | 'OTHER' }
 */
function classifyIntent(event) {
  const prompt = `
    ユーザーのテキストから意図を分類し、JSONで返してください。
    分類は "SET_REMINDER", "STOP_REMINDER", "OTHER" のいずれかです。
    ただし、基本的に "SET_REMINDER", "STOP_REMINDER"のどちらかで判断してください。

    - "SET_REMINDER": 新しいリマインダーを設定、または時間について言及している。
    - "STOP_REMINDER": リマインダーの停止、完了、感謝を伝えている。
      例:stop, erase, kill, キル, 消して, やめて, 終了, 完了,えんど,エンド,おわり,ありがとう,サンキュー,サンクス
    - "OTHER": 上記以外。

    例:
    - "3時間ごとに通知して" -> {"intent": "SET_REMINDER"}
    - "1日毎に教えろ" -> {"intent": "SET_REMINDER"}
    - "ほにゃららの件、1分毎にリマインダー" -> {"intent": "SET_REMINDER"}
    - "この件、もう大丈夫です" -> {"intent": "STOP_REMINDER"}
    - "ありがとう!" -> {"intent": "STOP_REMINDER"}
    - "ストップ" -> {"intent": "STOP_REMINDER"}
    - "こんにちは" -> {"intent": "OTHER"}

    ---
    テキスト: "${event.text}"
  `;
  const result = callGemini(event, prompt);
  try {
    return JSON.parse(result);
  } catch (e) {
    console.error('Classification Parse Error:', e.message);
    return { intent: 'OTHER' };
  }
}


/**
 * 新規リマインダーを登録する
 * @param {object} event Slackのイベントオブジェクト
 */
function registerNewReminder(event) {
  const threadTs = event.thread_ts || event.ts;
  const sheet = getSheet();
  const data = sheet.getDataRange().getValues();

  // 同じスレッドで既にリマインド中かチェック
  for (let i = 1; i < data.length; i++) {
    if (data[i][10] == threadTs && data[i][2] === 'リマインド中') {
      postConfirmationReply(event, 'この場においては、既に報せの務めが設定されております。');
      return;
    }
  }

  // Geminiでリマインダー情報を抽出
  const reminderInfo = extractReminderInfo(event);
  // リマインダーの間隔が読み取れない場合
  if (!reminderInfo || !reminderInfo.interval_hours) {
    postConfirmationReply(event, '報せる間隔を認識できませぬ。『一時間』や『三時間おき』のように、お示しくだされ。');
    return;
  }

  const intervalHours = reminderInfo.interval_hours;
  const content = reminderInfo.content;
  const startTimeISO = reminderInfo.start_time; // ISO 8601形式 (YYYY-MM-DDThh:mm:ss)
  const text = event.text.replace(/<@U09EU04DPGX>\s*/, '');
  const now = Math.floor(new Date().getTime() / 1000);

  let message = '';
  if (content) {
    message += `${content}件、`;
  }

  // 開始時刻の決定
  let nextReminderTime;
  let startTimeUnix = null;

  if (startTimeISO) {
    const parsedDate = new Date(startTimeISO);
    if (!isNaN(parsedDate.getTime())) {
      startTimeUnix = Math.floor(parsedDate.getTime() / 1000);
    }
  }

  if (startTimeUnix && startTimeUnix > now) {
    nextReminderTime = startTimeUnix;
    const startDate = new Date(startTimeUnix * 1000);
    const formattedStart = Utilities.formatDate(startDate, 'Asia/Tokyo', 'MM月dd日 HH時mm分');
    message += `${formattedStart} より、`;
  } else {
    nextReminderTime = now + (intervalHours * 60 * 60);
    message += 'これより';
  }

  const permalink = getPermalink(event.channel, event.ts);

  try {
    // スプレッドシートに書き込む
    sheet.appendRow([
      "'" + event.ts,
      formatUnixTimestamp(event.ts),
      'リマインド中',
      event.user,
      getUserRealName(event.user),
      extractUserIds(text),
      getRealNamesFromIds(extractUserIds(text)),
      text,
      event.channel,
      getChannelName(event.channel),
      "'" + threadTs,
      permalink,
      intervalHours,
      "'" + nextReminderTime,
      0,
      content
    ]);


    if (intervalHours >= 24) {
      const intervalDays = Math.round(intervalHours / 24);
      message += ` ${intervalDays} 日おきに`;
    } else if (intervalHours >= 1) {
      message += ` ${intervalHours} 時間おきに`;
    } else {
      const intervalMinutes = Math.round(intervalHours * 60);
      message += ` ${intervalMinutes} 分おきに`;
    }

    message += '、必ずや報せに参ります。';

    postConfirmationReply(event, message);

  } catch (e) {
    console.error('Error in registerNewReminder:', e.message);
  }
}


/**
 * リマインダーを完了済みにする
 * @param {object} event Slackのイベントオブジェクト
 */
function checkForCompletion(event) {
  const threadTs = event.thread_ts || event.ts;
  const sheet = getSheet();
  const data = sheet.getDataRange().getValues();
  let reminderFound = false;

  // そのスレッドのリマインダーを探す
  for (let i = 1; i < data.length; i++) {
    if (data[i][10] == threadTs && data[i][2] === 'リマインド中') {
      sheet.getRange(i + 1, 3).setValue('対応済み');
      postConfirmationReply(event, '報せの務め、完了いたしました。');
      reminderFound = true;
      break;
    }
  }
  if (!reminderFound) {
    postConfirmationReply(event, 'この場にて、拙者がお預かりしている報せの務めは見当たりませぬ。');
  }
}


/**
 * Geminiを使用して、テキストからリマインドの間隔と内容を抽出します。
 * @param {object} event Slackのイベントオブジェクト
 * @return {object} { interval_hours: number | null, content: string | null, start_time: string | null }
 */
function extractReminderInfo(event) {
  const now = new Date();
  const formattedNow = Utilities.formatDate(now, 'Asia/Tokyo', "yyyy-MM-dd'T'HH:mm:ss");

  const prompt = `
    以下のテキストから「リマインドの間隔」「リマインドのメッセージ内容」「リマインドを開始する日時」を抽出し、JSONで返してください。

    # 現在時刻
    ${formattedNow} (日本標準時)

    # 指示
    1. 間隔 (interval_hours):
       - 時間単位の数値に変換してください(例: 1分は0.016666、30分は0.5、2日は48)。
       - 認識できない場合は null を返してください。
    2. メッセージ内容 (content):
       - 基本的に完結な動詞の終止形で要約してください(例: 資料を作成する、メールを送る)。
       - 名詞単体となる場合、末尾に「についての」を必ず入れてください。
       - アラーム、リマインド、ストップなどの命令語は含めないでください。
       - 認識できない場合は null を返してください。
    3. 開始日時 (start_time):
       - 「明日から」「今日の21時から」「4月5日の9時から」といった表現がある場合、その日時を特定してください。
       - 結果は ISO 8601 形式 (YYYY-MM-DDThh:mm:ss) の文字列で返してください。
       - 明示的な指定がない場合や、過去の日時の場合は null を返してください。

    # 出力形式 (JSONのみを返してください)
    {"interval_hours": [数値またはnull], "content": "[文字列またはnull]", "start_time": "[ISO文字列またはnull]"}

    # 例(現在時刻は2026-04-01 12:00:00の場合)
    - "1時間おきに、家でろと言って" -> {"interval_hours": 1, "content": "家を出る", "start_time": null}
    - "明日の9時から1日ごとに教えて" -> {"interval_hours": 24, "content": null, "start_time": "2026-04-02T09:00:00"}
    - "30分毎にメールのリマインド" -> {"interval_hours": 0.5, "content": "メールについての", "start_time": null}
    - "立替の清算 14時から1分おきに" -> {"interval_hours": 0.017, "content": "立替の清算する", "start_time": "2026-04-01T14:00:00"}

    ---
    テキスト: "${event.text}"
  `;
  const result = callGemini(event, prompt);
  try {
    return JSON.parse(result);
  } catch (e) {
    console.error('Extraction Parse Error:', e.message);
    return { interval_hours: null, content: null, start_time: null };
  }
}


/**
 * Gemini APIを呼び出し、生成されたテキストを取得します。
 * @param {object} event Slackのイベントオブジェクト
 * @param {string} prompt プロンプト
 * @return {string} 生成されたテキスト
 */
function callGemini(event, prompt) {
  const properties = PropertiesService.getScriptProperties();
  const apiKey = properties.getProperty('GEMINI_API_KEY');
  const model = 'gemma-3-27b-it';
  const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;

  const payload = { 'contents': [{ 'parts': [{ 'text': prompt }] }] };
  const options = {
    'method': 'post',
    'contentType': 'application/json',
    'muteHttpExceptions': true,
    'payload': JSON.stringify(payload)
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const resJson = JSON.parse(response.getContentText());
    if (resJson.error) {
      console.error('Gemini API Error:', resJson.error.message);
      postConfirmationReply(event, '```Gemini API Error: ' + resJson.error.message + '```');
      return '{}';
    }
    if (!resJson.candidates || resJson.candidates.length === 0) {
      console.error('Gemini API returned no candidates');
      return '{}';
    }
    const resultText = resJson.candidates[0].content.parts[0].text;
    // JSONコードブロックを削除して返す
    return resultText.replace(/```json/gi, '').replace(/```/g, '').trim();
  } catch (e) {
    console.error('URL Fetch or Parse Error:', e.message);
    postConfirmationReply(event, '```GAS Execution Error: ' + e.message + '```');
    return '{}';
  }
}


/**
 * リマインダー記録用のスプレッドシートシートを取得します。
 * @return {GoogleAppsScript.Spreadsheet.Sheet}
 */
function getSheet() {
  const properties = PropertiesService.getScriptProperties();
  const spreadsheetId = properties.getProperty('SPREADSHEET_ID');
  return SpreadsheetApp.openById(spreadsheetId).getSheetByName('記録用シート');
}


/**
 * Unixタイムスタンプ(秒)を 'yyyy/MM/dd HH:mm:ss' 形式の文字列に変換します。
 * @param {string | number} unixTimestamp Unixタイムスタンプ(例: "1757922551.438709")
 * @returns {string} フォーマットされた日時文字列
 */
function formatUnixTimestamp(unixTimestamp) {
  const date = new Date(parseFloat(unixTimestamp) * 1000);
  return Utilities.formatDate(date, 'Asia/Tokyo', 'yyyy/MM/dd HH:mm:ss');
}


/**
 * イベントが既に処理済みかどうかを判定し、未処理ならキャッシュに登録します。
 * @param {string} event_ts イベントのタイムスタンプ
 * @return {boolean} 処理済みの場合はtrue、未処理の場合はfalse
 */
function isProcessed(event_ts) {
  const cache = CacheService.getScriptCache();
  if (cache.get(event_ts)) return true;
  cache.put(event_ts, 'processed', 600);
  return false;
}


/**
 * Slackにメッセージを投稿する
 * @param {object} event Slackのイベントオブジェクト
 * @param {string} message 送信するメッセージ内容
 */
function postConfirmationReply(event, message) {
  const threadTs = event.thread_ts || event.ts;
  const properties = PropertiesService.getScriptProperties();
  const token = properties.getProperty('SLACK_BOT_TOKEN');
  const url = 'https://slack.com/api/chat.postMessage';
  const payload = {
    channel: event.channel,
    text: message,
    thread_ts: threadTs,
    username: '報衛門',
  };
  const options = {
    method: 'post',
    contentType: 'application/json; charset=utf-8',
    headers: { 'Authorization': 'Bearer ' + token },
    payload: JSON.stringify(payload)
  };
  try {
    UrlFetchApp.fetch(url, options);
  } catch (e) {
    console.error('Slack postConfirmationReply Error:', e.message);
  }
}


/**
 * Slack投稿のパーマリンク(個別URL)を取得する
 * @param {string} channelId チャンネルID
 * @param {string} message_ts メッセージのタイムスタンプ
 * @return {string} 投稿のURL
 */
function getPermalink(channelId, message_ts) {
  const properties = PropertiesService.getScriptProperties();
  const token = properties.getProperty('SLACK_BOT_TOKEN');
  const url = `https://slack.com/api/chat.getPermalink?channel=${channelId}&message_ts=${message_ts}`;

  const options = {
    method: 'get',
    headers: { 'Authorization': 'Bearer ' + token }
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const json = JSON.parse(response.getContentText());
    return json.ok ? json.permalink : '';
  } catch (e) {
    console.error('Error in getPermalink:', e.message);
    return '';
  }
}


/**
 * SlackのユーザーIDから本名(real_name)を取得する
 * @param {string} userId ユーザーID (例: U01234567)
 * @return {string | null} ユーザーの本名。取得失敗時はnull。
 */
function getUserRealName(userId) {
  const properties = PropertiesService.getScriptProperties();
  const token = properties.getProperty('SLACK_BOT_TOKEN');
  const url = `https://slack.com/api/users.info?user=${userId}`;

  const options = {
    method: 'get',
    headers: { 'Authorization': 'Bearer ' + token }
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const json = JSON.parse(response.getContentText());

    if (json.ok && json.user) {
      return json.user.real_name;
    } else {
      console.error('Slack API error (users.info):', json.error || 'Unknown error');
      return null;
    }
  } catch (e) {
    console.error('Error in getUserRealName:', e.message);
    return null;
  }
}


/**
 * 文字列から全てのSlackユーザーIDを抽出し、カンマ区切りの文字列として返します。
 * 例: 「<@ID1>と<@ID2>に…」→ "ID1,ID2"
 * @param {string} text 解析対象の文字列
 * @returns {string} 抽出したユーザーIDをカンマで連結した文字列
 */
function extractUserIds(text) {
  if (!text) return '';
  const ids = [];
  const regex = /<@([A-Z0-9]+)>/g;
  let match;
  while ((match = regex.exec(text)) !== null) {
    ids.push(match[1]);
  }
  return ids.join(',');
}


/**
 * カンマ区切りのユーザーID文字列を受け取り、それぞれの本名をカンマ区切りの文字列で返します。
 * @param {string} idString カンマ区切りのユーザーID文字列 (例: "UP3ELBY05,U07N0UJ62VD")
 * @returns {string} ユーザーの本名をカンマで連結した文字列
 */
function getRealNamesFromIds(idString) {
  if (!idString) return '';
  const ids = idString.split(',');
  const names = ids.map(id => {
    return getUserRealName(id.trim()) || '不明なユーザー';
  });
  return names.join(',');
}


/**
 * SlackのチャンネルIDからチャンネル名を取得します。
 * @param {string} channelId チャンネルID (例: C12345678)
 * @return {string | null} チャンネル名。取得失敗時はnullを返す。
 */
function getChannelName(channelId) {
  const properties = PropertiesService.getScriptProperties();
  const token = properties.getProperty('SLACK_BOT_TOKEN');
  const url = `https://slack.com/api/conversations.info?channel=${channelId}`;
  const options = {
    method: 'get',
    headers: { 'Authorization': 'Bearer ' + token }
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const json = JSON.parse(response.getContentText());

    if (json.ok && json.channel) {
      return json.channel.name;
    } else {
      console.error('Slack API error (conversations.info):', json.error || 'Unknown error');
      return null;
    }
  } catch (e) {
    console.error('Error in getChannelName:', e.message);
    return null;
  }
}


/**
 * Slackイベントを受け取り、そのスレッド内の掃除(リマインド等の削除)を行います。
 * @param {object} event Slackのイベントオブジェクト
 */
function cleanUpThread(event) {
  const threadTs = event.thread_ts || event.ts;
  const channelId = event.channel;

  const properties = PropertiesService.getScriptProperties();
  const token = properties.getProperty('SLACK_BOT_TOKEN');

  try {
    // 自分のBot IDを取得
    const authUrl = 'https://slack.com/api/auth.test';
    const authResponse = UrlFetchApp.fetch(authUrl, {
      method: 'post',
      headers: { 'Authorization': 'Bearer ' + token }
    });
    const myBotId = JSON.parse(authResponse.getContentText()).bot_id;

    // スレッド内のメッセージを取得
    const repliesUrl = `https://slack.com/api/conversations.replies?channel=${channelId}&ts=${threadTs}`;
    const repliesResponse = UrlFetchApp.fetch(repliesUrl, {
      method: 'get',
      headers: { 'Authorization': 'Bearer ' + token }
    });

    const data = JSON.parse(repliesResponse.getContentText());
    if (!data.ok) {
      console.error('Thread replies fetch failed:', data.error);
      return;
    }

    // 特定の条件に合致する自分のメッセージを削除
    data.messages.forEach(msg => {
      // 条件:自分(Bot)の投稿 かつ テキストに「件」または「......」が含まれる かつ 「必ずや報せに参ります。」が含まれない
      const containsKeywords = msg.text.includes('件') || msg.text.includes('......');
      const isNotIntroduction = !msg.text.includes('必ずや報せに参ります。');

      if (msg.bot_id === myBotId && containsKeywords && isNotIntroduction) {
        deleteMessage(channelId, msg.ts, token);
      }
    });

  } catch (e) {
    console.error('Error in cleanUpThread:', e.message);
  }
}


/**
 * Slackの指定したメッセージを削除します。
 * @param {string} channelId チャンネルID
 * @param {string} ts メッセージのタイムスタンプ
 * @param {string} token Slackトークン
 */
function deleteMessage(channelId, ts, token) {
  const url = 'https://slack.com/api/chat.delete';
  const options = {
    method: 'post',
    contentType: 'application/json; charset=utf-8',
    headers: { 'Authorization': 'Bearer ' + token },
    payload: JSON.stringify({ channel: channelId, ts: ts })
  };
  try {
    UrlFetchApp.fetch(url, options);
    console.log(`Deleted message: ${ts}`);
  } catch (e) {
    console.error('Error deleting message:', e.message);
  }
}
sender.gs
/**
 * 期限切れのリマインダーを送信し、次回の時間を更新する
 * GASのトリガーで1分毎に実行する
 */
function sendScheduledReminders() {
  const properties = PropertiesService.getScriptProperties();
  const spreadsheetId = properties.getProperty('SPREADSHEET_ID');
  const sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName('記録用シート');
  const data = sheet.getDataRange().getValues();

  const now = Math.floor(new Date().getTime() / 1000);

  // ヘッダー行を除いてループ
  for (let i = 1; i < data.length; i++) {
    const row = data[i];

    const status = row[2];
    const userId = row[3];
    const ccuserId = row[5];
    const channelId = row[8];
    const threadTs = row[10];
    const intervalHours = row[12];
    const nextReminderTime = row[13];
    const reminderCount = row[14];
    const reminderContent = row[15];

    // 「リマインド中」で、実行時刻を過ぎている場合
    if (status === 'リマインド中' && nextReminderTime && now >= nextReminderTime) {

      let useAngerIcon = false;
      let reminderMessage = '';

      switch (reminderCount) {
        case 5:
          reminderMessage = '失礼。例の件、未だお済みではござりませぬか。一体、いかなるご事情か。仕舞いましたら、疾くご一報を。';
          useAngerIcon = true;
          break;
        case 10:
          reminderMessage = '例の件、一体いつまでお待たせすれば気が済みますか。拙者の務めを軽んじておられるか。迅速に済ませ、ご通達を。';
          useAngerIcon = true;
          break;
        case 15:
          reminderMessage = 'これほど報せても動かぬとは、主も地に落ちたもの。例の件、もはや為遂げる気概もおありでないか。';
          useAngerIcon = true;
          break;
        case 20:
          reminderMessage = 'これが何度目の報せと心得るか。例の件、最早拙者の忍耐も限界にござる。次が最後と思われよ。';
          useAngerIcon = true;
          break;
        case 25:
          reminderMessage = 'もう、お声がけはいたしませぬ。例の件、貴殿には荷が勝ちすぎた様子。このような主に仕えた拙者が愚かであった。';
          useAngerIcon = true;
          break;
        default:
          // 25回より大きい場合もこのメッセージ
          if (reminderCount > 25) {
            reminderMessage = '......';
            useAngerIcon = true;
          } else {
            // 通常のリマインドメッセージ
            reminderMessage = '差し出がましいとは存じますが、例の件、捗っておりますか。仕舞と相成りましたら、当方へメンションにてご通達を。';
          }
          break;
      }

      // リマインド内容の差し込み
      if (reminderContent && reminderCount <= 15) {
        reminderMessage = reminderMessage.replace('例の件', `${reminderContent}件`);
      }

      // CCの差し込み
      if (ccuserId) {
        reminderMessage = 'CC: ' + formatIdsToMentions(ccuserId) + '\n' + reminderMessage;
      }
      reminderMessage = `<@${userId}> \n` + reminderMessage;

      const success = postMessageToSlack(channelId, reminderMessage, threadTs.toString(), useAngerIcon);

      if (success) {
        // 次回の時間を計算して更新(時間単位)
        const newNextTime = now + (intervalHours * 60 * 60);
        sheet.getRange(i + 1, 14).setValue("'" + newNextTime); // I列を更新

        // 回数を更新
        sheet.getRange(i + 1, 15).setValue(reminderCount + 1); // J列を更新
      }
    }
  }
}


/**
 * Slackの指定したチャンネル・スレッドにメッセージを投稿する
 * @param {string} channelId チャンネルID
 * @param {string} text 送信するメッセージ
 * @param {string} threadTs 返信先スレッドのタイムスタンプ
 * @param {boolean} useAngerIcon アイコンを変更するかどうか
 * @return {boolean} 送信に成功したらtrue
 */
function postMessageToSlack(channelId, text, threadTs, useAngerIcon) {
  const properties = PropertiesService.getScriptProperties();
  const token = properties.getProperty('SLACK_BOT_TOKEN');
  const url = 'https://slack.com/api/chat.postMessage';

  const payload = {
    channel: channelId,
    text: text,
    thread_ts: threadTs,
    username: '報衛門',
  };

  // アイコンを変更する
  if (useAngerIcon) {
    payload.icon_url = 'https://pbs.twimg.com/media/GwxiWlJawAEfxCW?format=jpg&name=medium';
  }

  const options = {
    method: 'post',
    contentType: 'application/json; charset=utf-8',
    headers: { 'Authorization': 'Bearer ' + token },
    payload: JSON.stringify(payload)
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const jsonResponse = JSON.parse(response.getContentText());

    if (jsonResponse.ok) {
      console.log('Message sent successfully to channel: ' + channelId);
      return true;
    } else {
      console.error('Failed to send message: ' + jsonResponse.error);
      return false;
    }
  } catch (e) {
    console.error('Error sending message to Slack: ' + e.message);
    return false;
  }
}

/**
 * カンマ区切りのユーザーID文字列を、Slackのメンション形式(カンマ区切り)に変換します。
 * @param {string} idString カンマ区切りのユーザーID文字列 (例: "U01,U02")
 * @returns {string} Slackのメンション形式の文字列 (例: "<@U01>, <@U02>")
 */
function formatIdsToMentions(idString) {
  // 1. ID文字列が空の場合は、何もせずに空文字列を返す
  if (!idString) {
    return '';
  }

  // 2. カンマで文字列を分割して、IDの配列を作成する
  const ids = idString.split(',');

  // 3. 配列の各IDをメンション形式 <@ID> に変換する
  const mentions = ids.map(id => {
    // idの前後の余分な空白を削除
    const trimmedId = id.trim();
    return `<@${trimmedId}>`;
  });

  // 4. メンション形式の配列を「カンマ+半角スペース」で連結して返す
  return mentions.join(', ');
}

Discussion