自動加速.gs

Pasted Nov 30, 2026, 2:53 PM2 files1,766 lines

Scan to open on your phone

Point a camera at the QR code - it opens this exact paste, no app needed.

https://codepastes.com/zzgrs97n2b09fs8b
自動加速.gs
/**
 * YouTube Auto-Comment & Earthquake Alert Bot (Google Apps Script)
 *
 * 【概要】
 * 以下の3つの独立した機能を1つのGoogle Apps Scriptプロジェクトで稼働させる自動投稿Botです。
 * 1. 自動KSK機能   : 指定コメントへの返信としてセリフを1日ランダムな時刻に自動投稿(上限到達時は新スレッド自動作成)
 * 2. 天気コメント   : 全国主要都市の天気予報を新規コメントとして1日ランダムな時刻に自動投稿
 * 3. 地震情報通知   : P2P地震情報APIを監視し、検知時に新規コメント投稿(続報の自動編集・大きな地震の全地域返信対応)
 *
 * 【セットアップ手順】
 * 1. Google Apps Script (https://script.google.com/) で新規プロジェクトを作成し、本コードを貼り付けます。
 * 2. エディタ左メニューの「サービス」から「YouTube Data API v3」を追加します。
 * 3. 下記の `CONFIG` 内の `VIDEO_ID` と `INITIAL_COMMENT_IDS` をご自身の環境に合わせて書き換えます。
 * 4. 関数選択プルダウンから `installPersistentBot` を選択して実行し、初回権限を承認します。
 */

// ===================================================================
// ユーザー設定
// ===================================================================

const CONFIG = {
  // 対象の動画ID(YouTube動画URLの「v=」以降の11文字)
  VIDEO_ID: "niKAylKNIEI",

  // -----------------------------------------------------------------
  // 1. 自動KSK機能
  // -----------------------------------------------------------------
  KSK_ENABLED: true,
  INITIAL_COMMENT_IDS: ["UgwgOdkIkq9rc084tLN4AaABAg"], // 返信先となる親コメントID
  MIN_DAILY_KSK_POSTS: 10,          // 1日の最小投稿数
  MAX_DAILY_KSK_POSTS: 25,          // 1日の最大投稿数

  // -----------------------------------------------------------------
  // 2. 天気コメント機能
  // -----------------------------------------------------------------
  WEATHER_ENABLED: false,
  MIN_DAILY_WEATHER_POSTS: 6,       // 1日の最小投稿数
  MAX_DAILY_WEATHER_POSTS: 15,      // 1日の最大投稿数

  // -----------------------------------------------------------------
  // 3. 地震情報機能(開発途中)
  // -----------------------------------------------------------------
  EARTHQUAKE_ENABLED: false,
  EARTHQUAKE_THREAD_ID: "",         // 空文字: 新規コメント(続報編集&全地域返信あり) / ID指定: 指定スレッドへ返信
  EARTHQUAKE_POLL_MINUTES: 1,       // P2P地震情報APIの監視間隔(分)
  EARTHQUAKE_WINDOW_MINUTES: 15,    // 何分以内の地震情報を対象とするか
  EARTHQUAKE_MIN_SCALE: 10,         // 投稿する最小震度(10:震度1, 20:震度2, 30:震度3, 40:震度4, 45:震度5弱...)
  EARTHQUAKE_ALL_REGIONS_MIN_SCALE: 40, // 全観測地域を返信ツリーに投稿する最小震度(40:震度4以上)

  // -----------------------------------------------------------------
  // 共通設定
  // -----------------------------------------------------------------
  ADMIN_EMAIL: ""                   // 異常発生時の通知先メールアドレス(不要な場合は空文字のまま)
};

// ===================================================================
// システム内部定数(通常は変更不要)
// ===================================================================

const INTERNAL = {
  TIMEZONE: "Asia/Tokyo",
  QUOTA_SAFETY_LIMIT: 9000,         // 1日のYouTube APIクォータ安全上限(無料枠10,000)
  ERROR_THRESHOLD: 5,               // 連続エラー通知しきい値
  HEALTH_CHECK_HOUR: 3,             // 毎日のヘルスチェック実行時刻(時)
  PROPERTY_RETENTION_DAYS: 7,       // 日次ログプロパティの保持日数
  TRIGGER_SELF_HEAL_DAYS: 7,        // トリガー欠損時の自動復旧チェック間隔(日)

  // スケジュールチェック間隔・スレッド上限
  KSK_CHECK_INTERVAL_MINUTES: 5,
  WEATHER_CHECK_INTERVAL_MINUTES: 5,
  MAX_REPLIES_PER_THREAD: 450,
  AUTO_CREATE_THREAD: true,
  MAX_THREADS_PER_DAY: 2,
  MAX_STORED_THREADS: 50,

  // 自動KSKの統計混入率・重複回避履歴サイズ
  KSK_STATS_RATIO: 0.25,
  MAX_STATS_POSTS_PER_DAY: 15,
  KSK_HISTORY_SIZE: 25,
  KSK_MIN_LENGTH: 8,
  KSK_MAX_LENGTH: 200
};

// ===================================================================
// 自動KSK用セリフデータ(お好みのセリフに自由に差し替え可能)
// ===================================================================

const KSK_SCRIPT = `
魔理沙「霊夢のやつ、こんなところに呼び出して一体なんの用だ?」
アリス「あら、魔理沙こんにちは」
魔理沙「ようアリス」
パチュリー「私達もいるわ」
小悪魔「魔理沙さん、こんにちは」
魔理沙「パチュリーと小悪魔まで呼ばれたのか」
霊夢「ハイハーイ、みなさ~ん。今日もいい天気ですね~」
魔理沙「おい霊夢、何なんだよこの集まりは」
霊夢「皆さんにはこれから、相撲をとってもらいまーす」
アリス「お相撲?」
パチュリー「あー、あののこったのこったってやつ?」
小悪魔「いいですね!相撲、やりましょう!」
魔理沙「なんでお前はノリ気なんだよ。おかしいだろいきなり相撲って」
霊夢「なお優勝者には博麗神社に伝わる秘薬、水にサッと溶ける惚れ薬が贈呈されますので頑張ってくださーい」
アリス「私、やるわ!」
パチュリー「負けられない」
魔理沙「なぜだ、、、全員参加みたいな雰囲気になってきたぞ……はぁ、しょうがねぇなぁ」
霊夢「あんた達が本気で戦うと周囲に被害が出るでしょ。その対策よ」
小悪魔「異様な光景です」
魔理沙「なんで……こんなことになったんだぜ……」
霊夢「んでは、試合を行うあちらの土俵まで、移動して下さい」
アリス「なんであんな遠くにあるのよ!」
パチュリー「ちょ、あっちに置けばよかったんじゃない!?」
霊夢「さぁ1回戦はパチュリー対アリスよ、向い合って」
霊夢「西~~~~~~~~~ぃ、パチュリーノーレッジ~~~~~~~~」
パチュリー「そういうの要らないから!」
霊夢「それじゃあ四股踏みしてもらおうかな、パチュリーから」
パチュリー「へぇっ!?四股踏み?」
霊夢「片足を持ち上げて…」
霊夢「地面にズシンと足を降ろす!」
パチュリー「むきゅ!」
霊夢「2回戦 小悪魔対魔理沙」
霊夢「見合って見合って~はっきょーいのこった!」
小悪魔「どすこい!」
魔理沙「なんでちょっとマジなんだよお前!」
小悪魔「ふぅ~……ふぅ~。。。」
魔理沙「くそぅ、これでどうだ。おらあー!」
霊夢「決勝 アリス対魔理沙」
アリス「いくわよ、魔理沙!」
魔理沙「手加減しないぜ。うぉおおお」
霊夢「優勝おめでとう魔理沙。それでは表彰式を」
霊夢「痛みに耐えてよく頑張った、感動した」
霊夢「それでは幻想郷大相撲、次回の開催にご期待ください。さよなら」
魔理沙「次はねーよ!」
パチュリー「ウフフフ」
アリス「酢だこさん太郎食べられなくなるからやめて」
`;

let _kskLinesCache = null;

/**
 * セリフデータから有効な行のみを抽出・キャッシュして返します。
 */
function getKskLines() {
  if (_kskLinesCache) return _kskLinesCache;
  _kskLinesCache = KSK_SCRIPT.split("\n")
    .map(l => l.trim())
    .filter(t =>
      t &&
      /[「『].+[」』]$/.test(t) &&
      t.length >= INTERNAL.KSK_MIN_LENGTH &&
      t.length <= INTERNAL.KSK_MAX_LENGTH
    );
  return _kskLinesCache;
}

// ===================================================================
// 共通ユーティリティ
// ===================================================================

function todayStr() {
  return Utilities.formatDate(new Date(), INTERNAL.TIMEZONE, "yyyy-MM-dd");
}

function nowStr() {
  return Utilities.formatDate(new Date(), INTERNAL.TIMEZONE, "yyyy/MM/dd HH:mm:ss");
}

const log = m => console.log(m);
const warn = m => console.warn(m);
const err = m => console.error(m);

function safeArray(x) {
  return Array.isArray(x) ? x : [];
}

function hashText(text) {
  return Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, String(text))
    .map(b => (b & 0xFF).toString(16).padStart(2, "0")).join("");
}

function parseJstDateTime(str) {
  if (str == null || str === "") return null;
  const s = String(str).trim();
  const patterns = [
    "yyyy/MM/dd HH:mm:ss.SSS",
    "yyyy/MM/dd HH:mm:ss",
    "yyyy-MM-dd HH:mm:ss.SSS",
    "yyyy-MM-dd HH:mm:ss"
  ];
  for (const p of patterns) {
    try {
      const d = Utilities.parseDate(s, INTERNAL.TIMEZONE, p);
      if (d && !isNaN(d.getTime())) return d;
    } catch (e) { /* 次のフォーマットを試行 */ }
  }
  return null;
}

function isTimeBudgetExceeded(startTime) {
  if (Date.now() - startTime > 5 * 60 * 1000) {
    log("実行時間上限(5分)に近づいたため処理を中断しました。");
    return true;
  }
  return false;
}

function applyFinalText(text) {
  if (!text || typeof text !== "string") return "";
  return text.trim();
}

/**
 * 指定された目標件数分のランダムな投稿時刻(JST当日 00:00〜23:59)を生成します。
 */
function generateDailyRandomSchedule(today, now, targetCount) {
  const parts = today.split("-").map(Number);
  const startOfDayMs = Date.UTC(parts[0], parts[1] - 1, parts[2], 0, 0, 0) - 9 * 3600 * 1000;
  const endOfDayMs = startOfDayMs + 24 * 3600 * 1000 - 60 * 1000;
  const baseMs = Math.max(startOfDayMs, now.getTime());

  const remainMin = (endOfDayMs - baseMs) / 60000;
  if (remainMin < 30) {          // 残り30分未満なら今日は投稿しない
    log("[Auto KSK] 残り時間が短いため本日のスケジュール生成をスキップします。");
    return [];
  }
  const maxByTime = Math.max(1, Math.floor(remainMin / 30)); // 最低30分間隔
  const count = Math.min(targetCount, maxByTime);

  const schedule = [];
  if (baseMs < endOfDayMs) {
    for (let i = 0; i < count; i++) {
      schedule.push(baseMs + Math.floor(Math.random() * (endOfDayMs - baseMs)));
    }
    schedule.sort((a, b) => a - b);
  }
  return schedule;
}

// ===================================================================
// 機能別 有効/無効 状態判定
// ===================================================================

function isKskEnabled() {
  const override = PropertiesService.getScriptProperties().getProperty("KSK_ENABLED_OVERRIDE");
  if (override === "true") return true;
  if (override === "false") return false;
  return Boolean(CONFIG.KSK_ENABLED);
}

function isWeatherEnabled() {
  const override = PropertiesService.getScriptProperties().getProperty("WEATHER_ENABLED_OVERRIDE");
  if (override === "true") return true;
  if (override === "false") return false;
  return Boolean(CONFIG.WEATHER_ENABLED);
}

function isEarthquakeEnabled() {
  const override = PropertiesService.getScriptProperties().getProperty("EARTHQUAKE_ENABLED_OVERRIDE");
  if (override === "true") return true;
  if (override === "false") return false;
  return Boolean(CONFIG.EARTHQUAKE_ENABLED);
}

// ===================================================================
// APIクォータ・エラー制御
// ===================================================================

function recordQuota(units, type) {
  const props = PropertiesService.getScriptProperties();
  const today = todayStr();
  props.setProperty("QUOTA_USED_" + today,
    String(Number(props.getProperty("QUOTA_USED_" + today) || 0) + units));
  if (type) {
    const dk = "QUOTA_DETAIL_" + today;
    let d = {};
    try { d = JSON.parse(props.getProperty(dk) || "{}"); } catch (e) {}
    if (!d || typeof d !== "object") d = {};
    d[type] = (d[type] || 0) + units;
    d.total = (d.total || 0) + units;
    props.setProperty(dk, JSON.stringify(d));
  }
}

function isQuotaExceeded() {
  return Number(PropertiesService.getScriptProperties()
    .getProperty("QUOTA_USED_" + todayStr()) || 0) >= INTERNAL.QUOTA_SAFETY_LIMIT;
}

function getRemainingQuota() {
  const used = Number(PropertiesService.getScriptProperties()
    .getProperty("QUOTA_USED_" + todayStr()) || 0);
  return Math.max(0, INTERNAL.QUOTA_SAFETY_LIMIT - used);
}

function setRateLimitedToday() {
  PropertiesService.getScriptProperties().setProperty("RATE_LIMITED_" + todayStr(), "true");
}

function isRateLimitedToday() {
  return PropertiesService.getScriptProperties()
    .getProperty("RATE_LIMITED_" + todayStr()) === "true";
}

function setThreadsExhaustedToday() {
  PropertiesService.getScriptProperties().setProperty("THREADS_EXHAUSTED_" + todayStr(), "true");
}

function isThreadsExhaustedToday() {
  return PropertiesService.getScriptProperties()
    .getProperty("THREADS_EXHAUSTED_" + todayStr()) === "true";
}

// ===================================================================
// YouTube Data API v3 クライアント
// ===================================================================

function getMyChannelId() {
  const props = PropertiesService.getScriptProperties();
  const cached = props.getProperty("MY_CHANNEL_ID");
  if (cached) return cached;
  try {
    const ch = youtubeApi("get", "channels?part=id&mine=true", null, 1, "channels.list");
    const id = (safeArray(ch && ch.items)[0] || {}).id || "";
    if (id) props.setProperty("MY_CHANNEL_ID", id);
    return id;
  } catch (e) {
    warn("getMyChannelId: " + e.message);
    return "";
  }
}

function youtubeApi(method, endpoint, payload, units, type) {
  if (!CONFIG.VIDEO_ID || CONFIG.VIDEO_ID === "YOUR_YOUTUBE_VIDEO_ID") {
    throw new Error("CONFIG.VIDEO_ID が未設定です。対象の動画IDを設定してください。");
  }

  const options = {
    method: method,
    headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
    contentType: "application/json",
    muteHttpExceptions: true
  };
  if (payload) options.payload = JSON.stringify(payload);

  const res = UrlFetchApp.fetch("https://www.googleapis.com/youtube/v3/" + endpoint, options);
  const code = res.getResponseCode();
  const body = res.getContentText();

  if (code < 200 || code >= 300) {
    const lower = body.toLowerCase();
    if (code === 403 || code === 429) {
      if (lower.includes("quotaexceeded")) {
        setRateLimitedToday();
        err("YouTube API クォータ上限に到達しました (" + (type || "?") + ").");
      } else if (lower.includes("forbidden") || lower.includes("reply") ||
                 lower.includes("commentsdisabled")) {
        PropertiesService.getScriptProperties().setProperty("FORCE_THREAD_ADVANCE", "true");
      } else {
        setRateLimitedToday();
      }
    }
    throw new Error("YouTube API " + code + " [" + (type || "?") + "]: " + body);
  }

  let parsed;
  try {
    parsed = JSON.parse(body);
  } catch (e) {
    throw new Error("YouTube API レスポンスのJSON解析に失敗しました: " + body.slice(0, 200));
  }
  if (!parsed || typeof parsed !== "object") {
    throw new Error("YouTube API が不正なオブジェクトを返しました。");
  }

  recordQuota(units || 1, type || "other");
  return parsed;
}

/**
 * 動画への新規トップレベルコメントを1件投稿します。
 */
function postTopLevelComment(rawText) {
  if (typeof rawText !== "string" || !rawText) throw new Error("postTopLevelComment: text is empty");
  const text = applyFinalText(rawText);
  return youtubeApi("post", "commentThreads?part=snippet", {
    snippet: {
      videoId: CONFIG.VIDEO_ID,
      topLevelComment: { snippet: { textOriginal: text } }
    }
  }, 50, "commentThreads.insert").id;
}

/**
 * 指定された親コメントIDに対して返信を投稿します。
 */
function postReplyComment(parentId, rawText) {
  if (!parentId) throw new Error("postReplyComment: parentId is empty");
  if (typeof rawText !== "string" || !rawText) throw new Error("postReplyComment: text is empty");
  const text = applyFinalText(rawText);
  return youtubeApi("post", "comments?part=snippet", {
    snippet: { parentId: parentId, textOriginal: text }
  }, 50, "comments.insert").id;
}

/**
 * 既存のコメント(トップレベルまたは返信)を編集します。
 */
function updateCommentText(commentId, rawText) {
  if (!commentId) throw new Error("updateCommentText: commentId is empty");
  if (typeof rawText !== "string" || !rawText) throw new Error("updateCommentText: text is empty");
  const text = applyFinalText(rawText);
  return youtubeApi("put", "comments?part=snippet", {
    id: commentId,
    snippet: { textOriginal: text }
  }, 50, "comments.update").id;
}

/**
 * 指定されたコメントIDを削除します。
 */
function deleteCommentById(commentId) {
  if (!commentId) return;
  const options = {
    method: "delete",
    headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
    muteHttpExceptions: true
  };
  const res = UrlFetchApp.fetch(
    "https://www.googleapis.com/youtube/v3/comments?id=" + encodeURIComponent(commentId),
    options
  );
  if (res.getResponseCode() >= 200 && res.getResponseCode() < 300) {
    recordQuota(50, "comments.delete");
  } else {
    warn("deleteCommentById(" + commentId + ") HTTP " + res.getResponseCode());
  }
}

// ===================================================================
// 1. 自動KSK機能(返信のみ・スレッド自動作成維持)
// ===================================================================

let _threadIdsCache = null;

function getThreadIds() {
  if (_threadIdsCache) return _threadIdsCache.slice();
  const props = PropertiesService.getScriptProperties();
  const stored = props.getProperty("THREAD_IDS");
  let ids = null;
  if (stored) {
    try {
      const parsed = JSON.parse(stored);
      if (Array.isArray(parsed) && parsed.length > 0) ids = parsed;
    } catch (e) {}
  }
  if (!ids) {
    const seed = safeArray(CONFIG.INITIAL_COMMENT_IDS)
      .filter(id => id && id !== "YOUR_INITIAL_COMMENT_ID");
    if (seed.length === 0) {
      throw new Error("CONFIG.INITIAL_COMMENT_IDS が未設定です。有効なコメントIDを設定してください。");
    }
    ids = seed.slice();
    props.setProperty("THREAD_IDS", JSON.stringify(ids));
  }
  _threadIdsCache = ids;
  return ids.slice();
}

function saveThreadIds(ids) {
  const arr = safeArray(ids).slice(-INTERNAL.MAX_STORED_THREADS);
  _threadIdsCache = arr.slice();
  PropertiesService.getScriptProperties().setProperty("THREAD_IDS", JSON.stringify(arr));
}

/**
 * 指定されたスレッドIDを THREAD_IDS から除外し、アクティブIDも解除します。
 * 404 parentCommentNotFound 発生時のクリーンアップに使用します。
 */
function invalidateThreadId(commentId) {
  if (!commentId) return;
  const ids = getThreadIds().filter(id => id !== commentId);
  saveThreadIds(ids);
  const props = PropertiesService.getScriptProperties();
  const key = "ACTIVE_THREAD_ID_" + todayStr();
  if (props.getProperty(key) === commentId) {
    props.deleteProperty(key);
  }
  warn("[Auto KSK] 無効なスレッドIDを除外しました: " + commentId + "(残り " + ids.length + " 件)");
}

function getActiveThreadId() {
  const props = PropertiesService.getScriptProperties();
  const key = "ACTIVE_THREAD_ID_" + todayStr();
  const active = props.getProperty(key);
  const ids = getThreadIds();
  if (active && ids.includes(active)) return active;
  if (ids.length === 0) return "";
  props.setProperty(key, ids[0]);
  return ids[0];
}

function setActiveThreadId(id) {
  PropertiesService.getScriptProperties().setProperty("ACTIVE_THREAD_ID_" + todayStr(), id);
}

function advanceToNextThread(currentId) {
  const ids = getThreadIds();
  const idx = ids.indexOf(currentId);
  if (idx === -1 || idx >= ids.length - 1) return currentId;
  setActiveThreadId(ids[idx + 1]);
  return ids[idx + 1];
}

/**
 * コメントの存在確認と所有者確認を行います。
 * 存在しない場合は false を返します。
 */
function verifyCommentOwnership(commentId) {
  if (!commentId) return false;
  for (const ep of ["commentThreads", "comments"]) {
    try {
      const r = youtubeApi("get",
        ep + "?part=snippet&id=" + encodeURIComponent(commentId),
        null, 1, ep + ".list");
      const items = safeArray(r && r.items);
      if (items.length > 0) {
        const a = items[0]?.snippet?.topLevelComment?.snippet?.authorChannelId?.value
              || items[0]?.snippet?.authorChannelId?.value;
        if (a) return checkAuthor(a);
        return true;
      }
    } catch (e) { warn("verify(" + ep + "): " + e.message); }
  }
  // どちらのエンドポイントでも見つからなかった
  warn("verifyCommentOwnership: コメントが見つかりません: " + commentId);
  return false;
}

function checkAuthor(authorId) {
  try {
    const mine = getMyChannelId();
    if (!mine) return false;
    if (mine !== authorId) {
      warn("Author mismatch: " + authorId + " vs " + mine);
      return false;
    }
    return true;
  } catch (e) { return false; }
}

function getThreadReplyCount(commentId) {
  const r = youtubeApi("get",
    "commentThreads?part=snippet&id=" + encodeURIComponent(commentId),
    null, 1, "commentThreads.list");
  const items = safeArray(r && r.items);
  if (items.length === 0) throw new Error("スレッドが見つかりません。");
  return Number(items[0].snippet?.totalReplyCount || 0);
}

function canCreateMoreThreads() {
  const props = PropertiesService.getScriptProperties();
  const today = todayStr();
  if (Number(props.getProperty("THREADS_CREATED_" + today) || 0) >=
      INTERNAL.MAX_THREADS_PER_DAY) return false;
  return getRemainingQuota() >= 60;
}

function incrementThreadCreationCount() {
  const props = PropertiesService.getScriptProperties();
  const key = "THREADS_CREATED_" + todayStr();
  props.setProperty(key, String(Number(props.getProperty(key) || 0) + 1));
}

/**
 * 新規スレッドを作成し、THREAD_IDS に追加してアクティブに設定します。
 */
function createNewThread() {
  const opener = pickKskLine({ skipHistory: true });
  const newId = postTopLevelComment(opener);
  const ids = getThreadIds();
  ids.push(newId);
  saveThreadIds(ids);
  setActiveThreadId(newId);
  incrementThreadCreationCount();
  log("[Auto KSK] 新しい返信スレッドを作成しました: " + newId);
  return newId;
}

/**
 * 返信先として使用可能なスレッドIDを解決します。
 * 存在しないスレッドは自動的に THREAD_IDS から除外します。
 */
function resolveActiveThreadForReply() {
  const props = PropertiesService.getScriptProperties();
  let attempts = 0;
  const maxAttempts = Math.max(getThreadIds().length + 2, 3);

  while (attempts < maxAttempts) {
    attempts++;
    const commentId = getActiveThreadId();
    if (!commentId) break;

    let replyCount = 0;
    let exists = true;
    try {
      replyCount = getThreadReplyCount(commentId);
    } catch (e) {
      exists = false;
      warn("[Auto KSK] スレッドが存在しないため除外します: " + commentId);
    }

    if (!exists) {
      invalidateThreadId(commentId);
      continue;
    }

    if (props.getProperty("FORCE_THREAD_ADVANCE") === "true") {
      props.deleteProperty("FORCE_THREAD_ADVANCE");
      replyCount = INTERNAL.MAX_REPLIES_PER_THREAD;
    }

    if (replyCount < INTERNAL.MAX_REPLIES_PER_THREAD) return commentId;

    const next = advanceToNextThread(commentId);
    if (next !== commentId) continue;

    if (INTERNAL.AUTO_CREATE_THREAD && canCreateMoreThreads()) {
      return createNewThread();
    }

    setThreadsExhaustedToday();
    throw new Error("利用可能な返信スレッドがありません。");
  }

  // 有効な既存スレッドが1つもない
  if (INTERNAL.AUTO_CREATE_THREAD && canCreateMoreThreads()) {
    return createNewThread();
  }

  setThreadsExhaustedToday();
  throw new Error("利用可能な返信スレッドがありません(全IDが無効)。");
}

function pickKskLine({ skipHistory = false } = {}) {
  const lines = getKskLines();
  if (lines.length === 0) throw new Error("自動KSKのセリフプールが空です。");

  const props = PropertiesService.getScriptProperties();
  let history = [];
  try {
    history = JSON.parse(props.getProperty("KSK_HISTORY") || "[]");
    if (!Array.isArray(history)) history = [];
  } catch (e) { history = []; }

  const recentHashes = new Set(history);
  let candidates = lines.filter(l => !recentHashes.has(hashText(l)));

  if (candidates.length < 5) {
    candidates = lines.slice();
    history = [];
    log("[Auto KSK] セリフ履歴をリセットしました。");
  }

  const chosen = candidates[Math.floor(Math.random() * candidates.length)];

  if (!skipHistory) {
    history.push(hashText(chosen));
    if (history.length > INTERNAL.KSK_HISTORY_SIZE) {
      history = history.slice(-INTERNAL.KSK_HISTORY_SIZE);
    }
    props.setProperty("KSK_HISTORY", JSON.stringify(history));
  }

  return chosen;
}

function getVideoStatistics() {
  const r = youtubeApi("get",
    "videos?part=statistics&id=" + encodeURIComponent(CONFIG.VIDEO_ID),
    null, 1, "videos.list");
  const items = safeArray(r && r.items);
  if (items.length === 0) throw new Error("動画が見つかりません。");
  return items[0].statistics || {};
}

function generateStatsMessage() {
  try {
    const stats = getVideoStatistics();
    const fmt = n => Number(n || 0).toLocaleString("ja-JP");
    return [
      "📊 動画統計",
      "▶ " + fmt(stats.viewCount) + " 再生",
      "👍 " + fmt(stats.likeCount) + " 高評価",
      "💬 " + fmt(stats.commentCount) + " コメント",
      "",
      pickKskLine(),
      "",
      "🕒 " + nowStr()
    ].join("\n");
  } catch (e) {
    warn("generateStatsMessage: " + e.message);
    return null;
  }
}

function getKskTargetCount(today) {
  const props = PropertiesService.getScriptProperties();
  const key = "KSK_TARGET_COUNT_" + today;
  let t = Number(props.getProperty(key));
  if (!t) {
    t = Math.floor(Math.random() *
      (CONFIG.MAX_DAILY_KSK_POSTS - CONFIG.MIN_DAILY_KSK_POSTS + 1)) +
      CONFIG.MIN_DAILY_KSK_POSTS;
    props.setProperty(key, String(t));
  }
  return t;
}

function getKskTotalCount(today) {
  const props = PropertiesService.getScriptProperties();
  const s = Number(props.getProperty("KSK_POST_COUNT_" + today) || 0);
  const st = Number(props.getProperty("STATS_POST_COUNT_" + today) || 0);
  return s + st;
}

function getOrCreateDailyKskSchedule(today, now) {
  const props = PropertiesService.getScriptProperties();
  const key = "KSK_SCHEDULE_" + today;
  const stored = props.getProperty(key);
  if (stored) {
    try {
      const parsed = JSON.parse(stored);
      if (Array.isArray(parsed)) return parsed;
    } catch (e) {}
  }

  const target = getKskTargetCount(today);
  const schedule = generateDailyRandomSchedule(today, now, target);
  props.setProperty(key, JSON.stringify(schedule));
  log("[Auto KSK] 本日のランダム投稿スケジュールを生成しました(" + schedule.length + "件)");
  return schedule;
}

/**
 * 【自動KSK機能 メインタスク】
 * 1日の中でランダムに決定された予定時刻を過ぎたタイミングで返信投稿を行います。
 */
function runAutoKskTask(immediate) {
  if (!immediate && !isKskEnabled()) return;

  const lock = LockService.getScriptLock();
  if (!lock.tryLock(10000)) return;
  const startTime = Date.now();
  const props = PropertiesService.getScriptProperties();
  const today = todayStr();

  try {
    if (!immediate) {
      try { ensureTriggersExist(false); } catch (e) {}
    }

    if (isRateLimitedToday() || isQuotaExceeded() || isThreadsExhaustedToday()) return;

    const now = new Date();
    const target = getKskTargetCount(today);
    const current = getKskTotalCount(today);

    if (!immediate) {
      if (current >= target) return;
      const schedule = getOrCreateDailyKskSchedule(today, now);
      if (schedule.length === 0 || now.getTime() < schedule[0]) return;

      schedule.shift();
      props.setProperty("KSK_SCHEDULE_" + today, JSON.stringify(schedule));
    }

    if (isTimeBudgetExceeded(startTime)) return;

    const statsN = Number(props.getProperty("STATS_POST_COUNT_" + today) || 0);
    const useStats = !immediate &&
      statsN < INTERNAL.MAX_STATS_POSTS_PER_DAY &&
      Math.random() < INTERNAL.KSK_STATS_RATIO;

    if (!immediate) {
      Utilities.sleep(Math.floor(Math.random() * 45000));
      if (isTimeBudgetExceeded(startTime)) return;
    }

    let message = useStats ? generateStatsMessage() : null;
    const subType = message ? "stats" : "ksk";
    if (!message) {
      message = pickKskLine();
    }

    let threadId = resolveActiveThreadForReply();
    verifyCommentOwnership(threadId);

    let resultId;
    try {
      resultId = postReplyComment(threadId, message);
    } catch (e) {
      // 404 parentCommentNotFound の場合はスレッドを無効化して1回だけリトライ
      if (String(e.message || "").includes("parentCommentNotFound")) {
        warn("[Auto KSK] parentCommentNotFound を検知。スレッドを無効化して再試行します: " + threadId);
        invalidateThreadId(threadId);
        threadId = resolveActiveThreadForReply();
        verifyCommentOwnership(threadId);
        resultId = postReplyComment(threadId, message);
      } else {
        throw e;
      }
    }

    const countKey = (subType === "stats" ? "STATS_POST_COUNT_" : "KSK_POST_COUNT_") + today;
    props.setProperty(countKey, String(Number(props.getProperty(countKey) || 0) + 1));
    props.setProperty("LAST_KSK_POST_AT", new Date().toISOString());
    props.setProperty("CONSECUTIVE_ERRORS", "0");

    log("[Auto KSK Reply] Posted [" + subType + "]: " + resultId +
      " (" + (current + 1) + "/" + target + ")");

  } catch (error) {
    err("[Auto KSK Reply] " + (error.stack || error));
    const errors = Number(props.getProperty("CONSECUTIVE_ERRORS") || 0) + 1;
    props.setProperty("CONSECUTIVE_ERRORS", String(errors));
    if (errors === INTERNAL.ERROR_THRESHOLD) {
      notifyAdmin("連続エラー " + errors + " 回 (自動KSK機能)", String(error.stack || error));
    }
    throw error;
  } finally {
    lock.releaseLock();
  }
}

// ===================================================================
// 2. 天気コメント機能(新規コメントのみ・1日ランダム時刻投稿)
// ===================================================================

const CITIES = [
  { name: "札幌", lat: 43.0642, lon: 141.3469 },
  { name: "仙台", lat: 38.2682, lon: 140.8694 },
  { name: "東京", lat: 35.6762, lon: 139.6503 },
  { name: "名古屋", lat: 35.1815, lon: 136.9066 },
  { name: "大阪", lat: 34.6937, lon: 135.5023 },
  { name: "広島", lat: 34.3853, lon: 132.4553 },
  { name: "福岡", lat: 33.5902, lon: 130.4017 },
  { name: "那覇", lat: 26.2124, lon: 127.6809 }
];

const WEATHER_COMMENTS = [
  "過ごしやすい一日になりそうですね。",
  "傘を持って出かけたほうが安心かも。",
  "暑さ対策を忘れずに。",
  "冷え込むので上着があると安心です。",
  "洗濯物は室内干しが良さそう。",
  "お出かけ日和になりそうですね。",
  "空模様が変わりやすいので注意です。",
  "紫外線対策を忘れずに。",
  "深呼吸したくなるような空ですね。",
  "お散歩にはちょうどいい気温かも。",
  "気温差があるので体調管理に気をつけて。",
  "のんびり過ごすのが良さそうな一日。",
  "夜は冷えるので温かくして寝てくださいね。",
  "今日は空を見上げたくなる日かも。",
  "コーヒーがおいしい季節ですね。"
];

const WEATHER_CODE_LABELS = {
  0: ["快晴", "雲一つない青空", "よく晴れています"],
  1: ["晴れ", "おおむね晴れ", "日差しが届いています"],
  2: ["一部曇り", "晴れ時々曇り", "雲が広がりつつ"],
  3: ["曇り", "どんよりした空", "曇り空"],
  45: ["霧", "霧が出ています"],
  48: ["着氷性の霧", "冷たい霧"],
  51: ["弱い霧雨", "霧雨"],
  53: ["霧雨", "細かい霧雨"],
  55: ["強い霧雨", "本降りの霧雨"],
  61: ["弱い雨", "小雨", "ぱらつく雨"],
  63: ["雨", "本降りの雨"],
  65: ["強い雨", "激しい雨", "土砂降り"],
  71: ["弱い雪", "小雪"],
  73: ["雪", "本降りの雪"],
  75: ["強い雪", "大雪"],
  80: ["弱いにわか雨", "にわか雨"],
  81: ["にわか雨", "断続的なにわか雨"],
  82: ["強いにわか雨", "激しいにわか雨"],
  95: ["雷雨", "ゴロゴロ雷雨"],
  96: ["雷雨(雹)", "雷と雹"],
  99: ["激しい雷雨(雹)", "荒れた雷雨"]
};

function getWeatherForCity(city) {
  const cache = CacheService.getScriptCache();
  const cacheKey = "CITY_WEATHER_" + city.name;
  const cached = cache.get(cacheKey);
  if (cached) {
    try {
      const p = JSON.parse(cached);
      if (p && p.current && p.daily) return p;
    } catch (e) { /* 破損キャッシュは無視 */ }
  }

  try {
    const url = "https://api.open-meteo.com/v1/forecast" +
      "?latitude=" + city.lat +
      "&longitude=" + city.lon +
      "&current_weather=true" +
      "&daily=weathercode,temperature_2m_max,temperature_2m_min" +
      "&timezone=" + encodeURIComponent(INTERNAL.TIMEZONE) +
      "&forecast_days=2";
    const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true });
    if (res.getResponseCode() !== 200) {
      warn("City weather HTTP " + res.getResponseCode() + " (" + city.name + ")");
      return null;
    }
    const data = JSON.parse(res.getContentText());
    if (!data || !data.current_weather || !data.daily) return null;

    const result = { current: data.current_weather, daily: data.daily };
    cache.put(cacheKey, JSON.stringify(result), 1800);
    return result;
  } catch (e) {
    warn("getWeatherForCity(" + city.name + "): " + e.message);
    return null;
  }
}

function weatherVariants(code) {
  const arr = WEATHER_CODE_LABELS[code];
  if (!arr || arr.length === 0) return "不明";
  return arr[Math.floor(Math.random() * arr.length)];
}

function generateWeatherReport() {
  const city = CITIES[Math.floor(Math.random() * CITIES.length)];
  const data = getWeatherForCity(city);
  if (!data) return null;

  const cur = data.current || {};
  const day = data.daily || {};
  const codes = safeArray(day.weathercode);
  const maxs = safeArray(day.temperature_2m_max);
  const mins = safeArray(day.temperature_2m_min);
  const comment = WEATHER_COMMENTS[Math.floor(Math.random() * WEATHER_COMMENTS.length)];

  return [
    "【" + city.name + "の天気】",
    "現在: " + weatherVariants(cur.weathercode) + "、気温" + Math.round(Number(cur.temperature || 0)) + "°C",
    "明日: " + weatherVariants(codes[1]) +
      "(最高" + Math.round(Number(maxs[1] || 0)) +
      "°C / 最低" + Math.round(Number(mins[1] || 0)) + "°C)",
    "",
    comment,
    "",
    "🕒 " + nowStr()
  ].join("\n");
}

function getWeatherTargetCount(today) {
  const props = PropertiesService.getScriptProperties();
  const key = "WEATHER_TARGET_COUNT_" + today;
  let t = Number(props.getProperty(key));
  if (!t) {
    t = Math.floor(Math.random() *
      (CONFIG.MAX_DAILY_WEATHER_POSTS - CONFIG.MIN_DAILY_WEATHER_POSTS + 1)) +
      CONFIG.MIN_DAILY_WEATHER_POSTS;
    props.setProperty(key, String(t));
  }
  return t;
}

function getOrCreateDailyWeatherSchedule(today, now) {
  const props = PropertiesService.getScriptProperties();
  const key = "WEATHER_SCHEDULE_" + today;
  const stored = props.getProperty(key);
  if (stored) {
    try {
      const parsed = JSON.parse(stored);
      if (Array.isArray(parsed)) return parsed;
    } catch (e) {}
  }

  const target = getWeatherTargetCount(today);
  const schedule = generateDailyRandomSchedule(today, now, target);
  props.setProperty(key, JSON.stringify(schedule));
  log("[Weather Comment] 本日のランダム投稿スケジュールを生成しました(" + schedule.length + "件)");
  return schedule;
}

/**
 * 【天気コメント機能 メインタスク】
 * 1日の中でランダムに決定された予定時刻を過ぎたタイミングで新規コメント投稿を行います。
 */
function runWeatherCommentTask(immediate) {
  if (!immediate && !isWeatherEnabled()) return;

  const lock = LockService.getScriptLock();
  if (!lock.tryLock(10000)) return;
  const startTime = Date.now();
  const props = PropertiesService.getScriptProperties();
  const today = todayStr();

  try {
    const now = new Date();
    if (isRateLimitedToday() || isQuotaExceeded()) return;

    const target = getWeatherTargetCount(today);
    const current = Number(props.getProperty("WEATHER_POST_COUNT_" + today) || 0);

    if (!immediate) {
      if (current >= target) return;
      const schedule = getOrCreateDailyWeatherSchedule(today, now);
      if (schedule.length === 0 || now.getTime() < schedule[0]) return;

      schedule.shift();
      props.setProperty("WEATHER_SCHEDULE_" + today, JSON.stringify(schedule));

      Utilities.sleep(Math.floor(Math.random() * 45000));
      if (isTimeBudgetExceeded(startTime)) return;
    }

    const message = generateWeatherReport();
    if (!message) {
      warn("[Weather Comment] 天気データの取得に失敗したためスキップしました。");
      return;
    }

    const resultId = postTopLevelComment(message);

    props.setProperty("WEATHER_POST_COUNT_" + today, String(current + 1));
    props.setProperty("LAST_WEATHER_POST_AT", new Date().toISOString());
    props.setProperty("CONSECUTIVE_ERRORS", "0");

    log("[Weather Comment] Posted: " + resultId + " (" + (current + 1) + "/" + target + ")");

  } catch (error) {
    err("[Weather Comment] " + (error.stack || error));
    const errors = Number(props.getProperty("CONSECUTIVE_ERRORS") || 0) + 1;
    props.setProperty("CONSECUTIVE_ERRORS", String(errors));
    if (errors === INTERNAL.ERROR_THRESHOLD) {
      notifyAdmin("連続エラー " + errors + " 回 (天気機能)", String(error.stack || error));
    }
    throw error;
  } finally {
    lock.releaseLock();
  }
}

// ===================================================================
// 3. 地震情報機能(地震のみ・上限なし・続報自動編集&全地域返信)
// ===================================================================

function fetchRecentEarthquakes() {
  try {
    const res = UrlFetchApp.fetch("https://api.p2pquake.net/v2/jma/quake?limit=15",
      { muteHttpExceptions: true });
    if (res.getResponseCode() !== 200) {
      warn("P2P API HTTP " + res.getResponseCode());
      return [];
    }
    return safeArray(JSON.parse(res.getContentText()));
  } catch (e) {
    warn("fetchRecentEarthquakes: " + e.message);
    return [];
  }
}

function scaleToJapanese(s) {
  return {
    10: "震度1", 20: "震度2", 30: "震度3", 40: "震度4",
    45: "震度5弱", 50: "震度5強", 55: "震度6弱", 60: "震度6強", 70: "震度7"
  }[s] || ("震度コード" + s);
}

function buildEarthquakeEventKey(eq) {
  const e = (eq && eq.earthquake) || {};
  const h = e.hypocenter || {};
  const timeMinute = String(e.time || "").slice(0, 16); // "yyyy/MM/dd HH:mm"
  const hypoName = String(h.name || "").trim();
  return hypoName ? (timeMinute + "_" + hypoName) : (timeMinute + "_UNKNOWN_HYPO");
}

function getIssueTypeRank(issueType) {
  const ranks = {
    Other: 1,
    ScalePrompt: 2,         // 震度速報
    Destination: 3,         // 震源に関する情報
    ScaleAndDestination: 4, // 震度・震源に関する情報
    DetailScale: 5,         // 各地の震度に関する情報
    Foreign: 5              // 遠地地震に関する情報
  };
  return ranks[issueType] || 0;
}

function isNewerEarthquakeReport(existingState, eq) {
  if (!existingState) return true;
  const e = (eq && eq.earthquake) || {};
  const issue = (eq && eq.issue) || {};
  const newRank = getIssueTypeRank(issue.type);
  const oldRank = Number(existingState.rank || 0);
  const newIssueMs = (parseJstDateTime(eq.time) || new Date(0)).getTime();
  const oldIssueMs = Number(existingState.issueTimeMs || 0);
  const newMaxScale = Number(e.maxScale || 0);
  const oldMaxScale = Number(existingState.maxScale || 0);

  if (newRank < oldRank) return false;
  if (newRank === oldRank && newIssueMs <= oldIssueMs) return false;
  if (newIssueMs < oldIssueMs && newMaxScale <= oldMaxScale) return false;

  return true;
}

function formatEarthquakeMessage(eq, isEdited) {
  const e = (eq && eq.earthquake) || {};
  const h = e.hypocenter || {};
  const issue = (eq && eq.issue) || {};
  const points = safeArray(eq && eq.points);

  const scaleGroups = {};
  points.forEach(p => {
    const s = Number(p.scale);
    if (!s || s < 10) return;
    (scaleGroups[s] = scaleGroups[s] || []).push(p.addr);
  });

  const scaleOrder = [70, 60, 55, 50, 45, 40, 30, 20, 10];
  const scaleLines = [];
  scaleOrder.forEach(s => {
    const addrs = scaleGroups[s];
    if (!addrs || addrs.length === 0) return;
    const shown = addrs.slice(0, 5).join("、");
    const suffix = addrs.length > 5 ? " ほか" + (addrs.length - 5) + "地点" : "";
    scaleLines.push(scaleToJapanese(s) + ": " + shown + suffix);
  });

  const latRaw = (h.latitude != null && h.latitude !== "") ? String(h.latitude) : "";
  const lonRaw = (h.longitude != null && h.longitude !== "") ? String(h.longitude) : "";
  const lat = latRaw ? latRaw.replace(/^N/, "北緯").replace(/$/, "度") : "";
  const lon = lonRaw ? lonRaw.replace(/^E/, "東経").replace(/$/, "度") : "";
  const coord = (lat && lon) ? lat + " " + lon : "";

  const issueTypeMap = {
    ScalePrompt: "震度速報",
    Destination: "震源に関する情報",
    ScaleAndDestination: "震度・震源に関する情報",
    DetailScale: "各地の震度に関する情報",
    Foreign: "遠地地震に関する情報",
    Other: "その他の情報"
  };
  const issueType = issueTypeMap[issue.type] || issue.type || "";

  const tsunamiMap = {
    None: "心配なし",
    NonEffective: "若干の海面変動(被害の心配なし)",
    Watch: "津波注意報",
    Warning: "津波警報",
    MajorWarning: "大津波警報"
  };
  const tsunami = tsunamiMap[e.domesticTsunami] || e.domesticTsunami || "不明";

  let depth = h.depth != null ? String(h.depth) : "不明";
  if (depth && depth !== "不明" && !/km|ごく浅い/.test(depth)) depth = depth + "km";

  const lines = [
    isEdited ? "【地震情報(更新)】" : "【地震情報】",
    "発生時刻: " + (e.time != null ? String(e.time) : "不明"),
    "最大震度: " + scaleToJapanese(e.maxScale),
    "震源地: " + (h.name != null ? String(h.name) : "不明")
  ];
  if (coord) lines.push("震源: " + coord);
  lines.push("マグニチュード: " + (h.magnitude != null ? String(h.magnitude) : "不明"));
  lines.push("深さ: " + depth);
  if (issueType) lines.push("情報種別: " + String(issueType));
  lines.push("津波: " + tsunami);

  if (scaleLines.length > 0) {
    lines.push("");
    lines.push("■ 各地の震度(抜粋)");
    scaleLines.forEach(l => lines.push(l));
    if (Number(e.maxScale || 0) >= CONFIG.EARTHQUAKE_ALL_REGIONS_MIN_SCALE && points.length > 0) {
      lines.push("※全観測地域(全" + points.length + "地点)は返信欄に記載");
    }
  }
  lines.push("");
  lines.push("※P2P地震情報より自動投稿");
  lines.push("配信: " + (eq.time != null ? String(eq.time) : "不明"));
  return lines.join("\n");
}

function buildAllRegionsReplyChunks(eq) {
  const points = safeArray(eq && eq.points);
  if (points.length === 0) return [];

  const scaleGroups = {};
  points.forEach(p => {
    const s = Number(p.scale);
    if (!s || s < 10) return;
    const label = p.pref && !String(p.addr || "").startsWith(p.pref)
      ? (p.pref + p.addr)
      : String(p.addr || "");
    if (!label) return;
    (scaleGroups[s] = scaleGroups[s] || []).push(label);
  });

  const scaleOrder = [70, 60, 55, 50, 45, 40, 30, 20, 10];
  const sections = [];
  scaleOrder.forEach(s => {
    const addrs = scaleGroups[s];
    if (!addrs || addrs.length === 0) return;
    const uniqueAddrs = Array.from(new Set(addrs));
    sections.push("【" + scaleToJapanese(s) + "(" + uniqueAddrs.length + "地点)】\n" + uniqueAddrs.join("、"));
  });

  if (sections.length === 0) return [];

  const MAX_CHARS = 8500;
  const chunks = [];
  let current = "■ 各地の震度(全観測地域一覧)\n\n";

  for (const sec of sections) {
    if (current.length + sec.length + 2 <= MAX_CHARS) {
      current += sec + "\n\n";
    } else {
      if (current.trim()) chunks.push(current.trim());
      if (sec.length <= MAX_CHARS) {
        current = sec + "\n\n";
      } else {
        let rem = sec;
        while (rem.length > 0) {
          chunks.push(rem.slice(0, MAX_CHARS));
          rem = rem.slice(MAX_CHARS);
        }
        current = "";
      }
    }
  }
  if (current.trim()) chunks.push(current.trim());

  if (chunks.length > 1) {
    return chunks.map((c, idx) => c + "\n\n(" + (idx + 1) + "/" + chunks.length + ")");
  }
  return chunks;
}

function syncAllRegionsReplies(parentCommentId, eq, oldReplyIds) {
  safeArray(oldReplyIds).forEach(rid => {
    try { deleteCommentById(rid); } catch (e) {}
  });

  const maxScale = Number(eq?.earthquake?.maxScale || 0);
  if (maxScale < CONFIG.EARTHQUAKE_ALL_REGIONS_MIN_SCALE) return [];

  const chunks = buildAllRegionsReplyChunks(eq);
  const newReplyIds = [];
  for (const chunk of chunks) {
    try {
      const rid = postReplyComment(parentCommentId, chunk);
      newReplyIds.push(rid);
    } catch (e) {
      err("[Earthquake] 全地域返信の投稿に失敗: " + e.message);
    }
  }
  return newReplyIds;
}

/**
 * 【地震情報機能 メインタスク】
 * 1日の投稿上限なし・続報の自動編集・大きな地震の全地域返信投稿を行います。
 */
function runEarthquakeTask() {
  if (!isEarthquakeEnabled()) return;

  const lock = LockService.getScriptLock();
  if (!lock.tryLock(5000)) return;

  try {
    const props = PropertiesService.getScriptProperties();
    const today = todayStr();
    if (isQuotaExceeded() || isRateLimitedToday()) return;

    const quakes = fetchRecentEarthquakes();
    if (quakes.length === 0) return;

    const now = new Date();
    let eqStates = {};
    try {
      eqStates = JSON.parse(props.getProperty("EQ_EVENT_STATES") || "{}");
      if (!eqStates || typeof eqStates !== "object") eqStates = {};
    } catch (e) { eqStates = {}; }

    const cutoffMs = now.getTime() - 48 * 3600 * 1000;
    Object.keys(eqStates).forEach(k => {
      if (Number(eqStates[k]?.updatedAtMs || 0) < cutoffMs) delete eqStates[k];
    });

    const sortedQuakes = quakes.slice().reverse();

    for (const eq of sortedQuakes) {
      if (!eq || eq.code !== 551) continue;
      if (!eq.earthquake || eq.earthquake.time == null) continue;

      const issueTime = parseJstDateTime(eq.time);
      if (!issueTime) continue;

      const diff = (now - issueTime) / 60000;
      if (diff > CONFIG.EARTHQUAKE_WINDOW_MINUTES || diff < -2) continue;
      if (Number(eq.earthquake.maxScale || 0) < CONFIG.EARTHQUAKE_MIN_SCALE) continue;

      const eventKey = buildEarthquakeEventKey(eq);
      const timeMinute = String(eq.earthquake.time || "").slice(0, 16);
      const unknownKey = timeMinute + "_UNKNOWN_HYPO";
      if (eventKey !== unknownKey && !eqStates[eventKey] && eqStates[unknownKey]) {
        eqStates[eventKey] = eqStates[unknownKey];
        delete eqStates[unknownKey];
      }

      const existing = eqStates[eventKey];
      if (existing && Array.isArray(existing.seenIds) && existing.seenIds.includes(eq.id)) {
        continue;
      }
      if (!isNewerEarthquakeReport(existing, eq)) {
        log("[Earthquake] 古い続報のためスキップしました: " + eventKey + " (" + (eq.issue?.type || "") + ")");
        continue;
      }

      try {
        let commentId = existing ? existing.commentId : null;
        let replyIds = existing ? safeArray(existing.replyIds) : [];
        const isUpdate = Boolean(commentId);
        const text = formatEarthquakeMessage(eq, isUpdate);

        if (isUpdate) {
          updateCommentText(commentId, text);
          log("[Earthquake] 既存コメントを更新しました: " + commentId + " (" + eventKey + ")");
        } else {
          commentId = CONFIG.EARTHQUAKE_THREAD_ID
            ? postReplyComment(CONFIG.EARTHQUAKE_THREAD_ID, text)
            : postTopLevelComment(text);
          log("[Earthquake] 新規投稿しました: " + commentId + " (" + eventKey + ")");
          const cnt = Number(props.getProperty("EQ_POST_COUNT_" + today) || 0);
          props.setProperty("EQ_POST_COUNT_" + today, String(cnt + 1));
        }

        if (!CONFIG.EARTHQUAKE_THREAD_ID && commentId) {
          replyIds = syncAllRegionsReplies(commentId, eq, replyIds);
        }

        const seenIds = existing && Array.isArray(existing.seenIds) ? existing.seenIds.slice() : [];
        if (eq.id) seenIds.push(eq.id);

        eqStates[eventKey] = {
          commentId: commentId,
          replyIds: replyIds,
          rank: getIssueTypeRank(eq.issue?.type),
          issueTimeMs: issueTime.getTime(),
          maxScale: Number(eq.earthquake.maxScale || 0),
          seenIds: seenIds.slice(-20),
          updatedAtMs: now.getTime()
        };

        props.setProperty("EQ_EVENT_STATES", JSON.stringify(eqStates));
        props.setProperty("EQ_LAST_POST_AT", now.toISOString());
        break;
      } catch (e) {
        err("[Earthquake] Post/Update failed: " + e.message);
      }
    }
  } catch (e) {
    err("[Earthquake] " + (e.stack || e));
  } finally {
    lock.releaseLock();
  }
}

// ===================================================================
// 管理・オンオフ切り替え・ステータス確認関数(GASエディタから直接実行可能)
// ===================================================================

function enableAutoKsk() {
  PropertiesService.getScriptProperties().setProperty("KSK_ENABLED_OVERRIDE", "true");
  ensureSingleTrigger("runAutoKskTask", INTERNAL.KSK_CHECK_INTERVAL_MINUTES);
  log("✅ 自動KSK機能(返信のみ・ランダム時刻投稿)をオンにしました。");
}

function disableAutoKsk() {
  PropertiesService.getScriptProperties().setProperty("KSK_ENABLED_OVERRIDE", "false");
  removeTriggersByHandler("runAutoKskTask");
  log("🛑 自動KSK機能をオフにしました。");
}

function enableWeather() {
  PropertiesService.getScriptProperties().setProperty("WEATHER_ENABLED_OVERRIDE", "true");
  ensureSingleTrigger("runWeatherCommentTask", INTERNAL.WEATHER_CHECK_INTERVAL_MINUTES);
  log("✅ 天気コメント機能(新規コメントのみ・ランダム時刻投稿)をオンにしました。");
}

function disableWeather() {
  PropertiesService.getScriptProperties().setProperty("WEATHER_ENABLED_OVERRIDE", "false");
  removeTriggersByHandler("runWeatherCommentTask");
  log("🛑 天気コメント機能をオフにしました。");
}

function enableEarthquake() {
  PropertiesService.getScriptProperties().setProperty("EARTHQUAKE_ENABLED_OVERRIDE", "true");
  ensureSingleTrigger("runEarthquakeTask", CONFIG.EARTHQUAKE_POLL_MINUTES);
  log("✅ 地震情報機能(地震のみ)をオンにしました。");
}

function disableEarthquake() {
  PropertiesService.getScriptProperties().setProperty("EARTHQUAKE_ENABLED_OVERRIDE", "false");
  removeTriggersByHandler("runEarthquakeTask");
  log("🛑 地震情報機能をオフにしました。");
}

/**
 * 関数によるオンオフ上書き設定をすべて解除し、CONFIG の初期設定に戻します。
 */
function resetAllFeatureOverrides() {
  const props = PropertiesService.getScriptProperties();
  props.deleteProperty("KSK_ENABLED_OVERRIDE");
  props.deleteProperty("WEATHER_ENABLED_OVERRIDE");
  props.deleteProperty("EARTHQUAKE_ENABLED_OVERRIDE");
  installPersistentBot();
  log("🔄 全機能のオン/オフ上書きを解除し、CONFIG の設定に戻しました。");
}

/**
 * 全3機能の現在のオン/オフ状態・次回予定時刻・本日の投稿数を一覧表示します。
 */
function showBotStatus() {
  const props = PropertiesService.getScriptProperties();
  const today = todayStr();
  const triggers = safeArray(ScriptApp.getProjectTriggers()).map(t => t.getHandlerFunction());

  const kCnt = getKskTotalCount(today);
  const wCnt = Number(props.getProperty("WEATHER_POST_COUNT_" + today) || 0);
  const eCnt = Number(props.getProperty("EQ_POST_COUNT_" + today) || 0);

  log("==========================================");
  log("【1. 自動KSK機能(返信のみ・ランダム時刻)】");
  log("  状態: " + (isKskEnabled() ? "🟢 ON" : "🔴 OFF") +
    " (トリガー: " + (triggers.includes("runAutoKskTask") ? "あり" : "なし") + ")");
  log("  本日投稿: " + kCnt + " / " + getKskTargetCount(today));
  log("  登録スレッドID: " + JSON.stringify(getThreadIds()));
  const schedRaw = props.getProperty("KSK_SCHEDULE_" + today);
  if (schedRaw) {
    try {
      const sched = JSON.parse(schedRaw);
      if (Array.isArray(sched) && sched.length > 0) {
        const nextTime = Utilities.formatDate(new Date(sched[0]), INTERNAL.TIMEZONE, "HH:mm");
        log("  次回予定時刻: " + nextTime + " 頃(残り予定 " + sched.length + " 件)");
      }
    } catch (e) {}
  }

  log("【2. 天気コメント機能(新規コメントのみ・ランダム時刻)】");
  log("  状態: " + (isWeatherEnabled() ? "🟢 ON" : "🔴 OFF") +
    " (トリガー: " + (triggers.includes("runWeatherCommentTask") ? "あり" : "なし") + ")");
  log("  本日投稿: " + wCnt + " / " + getWeatherTargetCount(today));
  const wSchedRaw = props.getProperty("WEATHER_SCHEDULE_" + today);
  if (wSchedRaw) {
    try {
      const wSched = JSON.parse(wSchedRaw);
      if (Array.isArray(wSched) && wSched.length > 0) {
        const nextWTime = Utilities.formatDate(new Date(wSched[0]), INTERNAL.TIMEZONE, "HH:mm");
        log("  次回予定時刻: " + nextWTime + " 頃(残り予定 " + wSched.length + " 件)");
      }
    } catch (e) {}
  }

  log("【3. 地震情報機能(地震のみ・上限なし・続報編集&全地域返信)】");
  log("  状態: " + (isEarthquakeEnabled() ? "🟢 ON" : "🔴 OFF") +
    " (トリガー: " + (triggers.includes("runEarthquakeTask") ? "あり" : "なし") + ")");
  log("  本日新規地震投稿: " + eCnt + " 件(上限なし)");
  log("==========================================");
}

// ===================================================================
// トリガー・セットアップ・ヘルスチェック
// ===================================================================

function ensureSingleTrigger(handlerName, intervalMinutes) {
  const exists = safeArray(ScriptApp.getProjectTriggers())
    .some(t => t.getHandlerFunction() === handlerName);
  if (!exists) {
    ScriptApp.newTrigger(handlerName)
      .timeBased().everyMinutes(intervalMinutes).create();
    log("トリガーを作成しました: " + handlerName + " (" + intervalMinutes + "分間隔)");
  }
}

function removeTriggersByHandler(handlerName) {
  let removed = 0;
  safeArray(ScriptApp.getProjectTriggers()).forEach(t => {
    if (t.getHandlerFunction() === handlerName) {
      ScriptApp.deleteTrigger(t);
      removed++;
    }
  });
  return removed;
}

/**
 * Botの初回セットアップおよび全トリガーの再構築を行います。
 */
function installPersistentBot() {
  stopBot();
  try { getMyChannelId(); } catch (e) {}

  if (isKskEnabled()) {
    ensureSingleTrigger("runAutoKskTask", INTERNAL.KSK_CHECK_INTERVAL_MINUTES);
  }
  if (isWeatherEnabled()) {
    ensureSingleTrigger("runWeatherCommentTask", INTERNAL.WEATHER_CHECK_INTERVAL_MINUTES);
  }
  if (isEarthquakeEnabled()) {
    ensureSingleTrigger("runEarthquakeTask", CONFIG.EARTHQUAKE_POLL_MINUTES);
  }

  ScriptApp.newTrigger("healthCheck")
    .timeBased().atHour(INTERNAL.HEALTH_CHECK_HOUR).everyDays(1).create();

  const props = PropertiesService.getScriptProperties();
  props.setProperty("INSTALLED_AT", new Date().toISOString());
  props.setProperty("CONSECUTIVE_ERRORS", "0");
  props.setProperty("LAST_HEALTH_CHECK", new Date().toISOString());

  const summary = [
    "1. 自動KSK(返信のみ): " + (isKskEnabled() ? "有効" : "無効") + " / プール " + getKskLines().length + " 行",
    "2. 天気(新規コメントのみ): " + (isWeatherEnabled() ? "有効(" + CITIES.length + "都市)" : "無効"),
    "3. 地震(地震のみ): " + (isEarthquakeEnabled() ? "有効" : "無効")
  ].join("\n");

  notifyAdmin("✅ Bot 開始(機能分離モード)", summary);
  log("Installed.\n" + summary);
}

/**
 * すべてのBotトリガーを停止・削除します。
 */
function stopBot() {
  let n = 0;
  const targets = [
    "runAutoKskTask",
    "runWeatherCommentTask",
    "runEarthquakeTask",
    "healthCheck"
  ];
  ScriptApp.getProjectTriggers().forEach(t => {
    if (targets.includes(t.getHandlerFunction())) {
      ScriptApp.deleteTrigger(t);
      n++;
    }
  });
  log("Stopped. Removed triggers: " + n);
}

function healthCheck() {
  const props = PropertiesService.getScriptProperties();
  const now = new Date();
  const report = [];
  let hasProblem = false;

  try {
    const tr = ensureTriggersExist(true);
    if (tr.repaired) {
      report.push("⚠️ トリガー再作成: " + tr.created.join(", "));
      hasProblem = true;
    }

    const today = todayStr();
    report.push("1. 自動KSK(返信): " + (isKskEnabled() ? "ON" : "OFF") +
      " / 本日 " + getKskTotalCount(today) + " 件");
    report.push("2. 天気(新規コメ): " + (isWeatherEnabled() ? "ON" : "OFF") +
      " / 本日 " + Number(props.getProperty("WEATHER_POST_COUNT_" + today) || 0) + " 件");
    report.push("3. 地震(地震のみ): " + (isEarthquakeEnabled() ? "ON" : "OFF") +
      " / 本日 " + Number(props.getProperty("EQ_POST_COUNT_" + today) || 0) + " 件");

    const quota = Number(props.getProperty("QUOTA_USED_" + today) || 0);
    report.push((quota >= INTERNAL.QUOTA_SAFETY_LIMIT ? "⚠️" : "✓") +
      " クォータ: " + quota + " / " + INTERNAL.QUOTA_SAFETY_LIMIT);

    const errCnt = Number(props.getProperty("CONSECUTIVE_ERRORS") || 0);
    report.push((errCnt > 0 ? "⚠️" : "✓") + " 連続エラー: " + errCnt);

    const removed = cleanupOldProperties();
    if (removed > 0) report.push("✓ 古いプロパティ削除: " + removed);

    try {
      youtubeApi("get", "channels?part=id&mine=true", null, 1, "channels.list");
      report.push("✓ API疎通 OK");
    } catch (e) { report.push("❌ API: " + e.message); hasProblem = true; }

    props.setProperty("LAST_HEALTH_CHECK", now.toISOString());
    if (hasProblem) notifyAdmin("⚠️ ヘルスチェック", report.join("\n"));
    log(report.join("\n"));
  } catch (e) {
    err(e.stack || e);
    notifyAdmin("❌ ヘルスチェック失敗", String(e.stack || e));
    try { ensureTriggersExist(true); } catch (_) {}
  }
}

function ensureTriggersExist(force) {
  const props = PropertiesService.getScriptProperties();
  const h = safeArray(ScriptApp.getProjectTriggers()).map(t => t.getHandlerFunction());
  const needKsk = isKskEnabled() && !h.includes("runAutoKskTask");
  const needWeather = isWeatherEnabled() && !h.includes("runWeatherCommentTask");
  const needEq = isEarthquakeEnabled() && !h.includes("runEarthquakeTask");
  const needHealth = !h.includes("healthCheck");

  if (!force) {
    const last = props.getProperty("LAST_TRIGGER_HEAL");
    if (last && (new Date() - new Date(last)) / 86400000 <
        INTERNAL.TRIGGER_SELF_HEAL_DAYS) {
      return { repaired: false, created: [] };
    }
  }

  const created = [];
  if (needKsk) {
    ensureSingleTrigger("runAutoKskTask", INTERNAL.KSK_CHECK_INTERVAL_MINUTES);
    created.push("runAutoKskTask");
  }
  if (needWeather) {
    ensureSingleTrigger("runWeatherCommentTask", INTERNAL.WEATHER_CHECK_INTERVAL_MINUTES);
    created.push("runWeatherCommentTask");
  }
  if (needEq) {
    ensureSingleTrigger("runEarthquakeTask", CONFIG.EARTHQUAKE_POLL_MINUTES);
    created.push("runEarthquakeTask");
  }
  if (needHealth) {
    ScriptApp.newTrigger("healthCheck")
      .timeBased().atHour(INTERNAL.HEALTH_CHECK_HOUR).everyDays(1).create();
    created.push("healthCheck");
  }
  if (created.length) props.setProperty("LAST_TRIGGER_HEAL", new Date().toISOString());
  return { repaired: created.length > 0, created };
}

function cleanupOldProperties() {
  const props = PropertiesService.getScriptProperties();
  const all = props.getProperties();
  if (!all || typeof all !== "object") return 0;
  const now = new Date();
  const prefixes = [
    "QUOTA_USED_", "QUOTA_DETAIL_", "RATE_LIMITED_", "THREADS_EXHAUSTED_", "THREADS_CREATED_",
    "EQ_POST_COUNT_", "KSK_POST_COUNT_", "STATS_POST_COUNT_", "WEATHER_POST_COUNT_",
    "KSK_SCHEDULE_", "WEATHER_SCHEDULE_", "KSK_TARGET_COUNT_", "WEATHER_TARGET_COUNT_",
    "ACTIVE_THREAD_ID_"
  ];
  let removed = 0;
  Object.keys(all).forEach(k => {
    if (!prefixes.some(p => k.startsWith(p))) return;
    const m = k.match(/(\d{4}-\d{2}-\d{2})$/);
    if (!m) return;
    if ((now - new Date(m[1])) / 86400000 > INTERNAL.PROPERTY_RETENTION_DAYS) {
      props.deleteProperty(k);
      removed++;
    }
  });
  return removed;
}

function notifyAdmin(subject, body) {
  if (!CONFIG.ADMIN_EMAIL) return;
  try {
    MailApp.sendEmail({
      to: CONFIG.ADMIN_EMAIL,
      subject: "[YouTubeBot] " + subject,
      body: body
    });
  } catch (e) { err("notifyAdmin: " + e.message); }
}

// ===================================================================
// 動作確認用テスト関数(手動実行用)
// ===================================================================

function testKskPool() {
  const lines = getKskLines();
  console.log("自動KSKセリフプール件数: " + lines.length);
  lines.slice(0, 5).forEach((l, i) => console.log((i + 1) + ": " + l));
}

function testWeatherReport() {
  console.log(generateWeatherReport() || "(生成失敗)");
}

function testPostAutoKskNow() {
  runAutoKskTask(true);
}

function testPostWeatherCommentNow() {
  runWeatherCommentTask(true);
}

function testPostEarthquakeNow() {
  runEarthquakeTask();
}

/**
 * デバッグ用:動画の有効なトップレベルコメントを一覧表示します。
 * 404が続く場合はこれを実行し、表示されたIDを CONFIG.INITIAL_COMMENT_IDS に設定してください。
 */
function listValidTopLevelComments() {
  const res = youtubeApi("get",
    "commentThreads?part=snippet&videoId=" + encodeURIComponent(CONFIG.VIDEO_ID) +
    "&maxResults=20&order=time",
    null, 1, "commentThreads.list");
  (res.items || []).forEach(item => {
    const s = item.snippet.topLevelComment.snippet;
    console.log(item.id, "|", s.authorDisplayName, "|", s.textDisplay.slice(0, 30));
  });
}
function debugTriggersAndSchedule() {
  // トリガー一覧
  const triggers = ScriptApp.getProjectTriggers()
    .filter(t => t.getHandlerFunction() === "runAutoKskTask");
  console.log("runAutoKskTask のトリガー数:", triggers.length);
  triggers.forEach(t => console.log(" - ID:", t.getUniqueId(), "type:", t.getEventType()));

  // 今日のスケジュール残
  const props = PropertiesService.getScriptProperties();
  const today = Utilities.formatDate(new Date(), "Asia/Tokyo", "yyyy-MM-dd");
  const raw = props.getProperty("KSK_SCHEDULE_" + today);
  if (raw) {
    const sched = JSON.parse(raw);
    console.log("残り予定件数:", sched.length);
    sched.slice(0, 10).forEach(ms =>
      console.log(" 予定:", Utilities.formatDate(new Date(ms), "Asia/Tokyo", "HH:mm:ss")));
  } else {
    console.log("スケジュール未生成");
  }
}
function cleanupKskTriggers() {
  let n = 0;
  ScriptApp.getProjectTriggers().forEach(t => {
    if (t.getHandlerFunction() === "runAutoKskTask") {
      ScriptApp.deleteTrigger(t);
      n++;
    }
  });
  console.log("削除した runAutoKskTask トリガー:", n);
  ensureSingleTrigger("runAutoKskTask", INTERNAL.KSK_CHECK_INTERVAL_MINUTES);
  console.log("トリガーを1つに再作成しました。");
}

56,922 chars · codepastes.com