fromis_9/backend/services/youtube-scheduler.js
caadiq e216539f34 feat(bot): studiofromis_9 채널 봇 추가 및 cron 표현식 지원
- .env에 YouTube API 키 추가
- bots 테이블에 channel_id, rss_url, cron_expression 컬럼 추가
- youtube-scheduler.js: cron_expression 파라미터 지원
- youtube-bot.js: bots 테이블에서 직접 조회, Shorts 필터링 제거
- studiofromis_9 봇 등록 (채널: UCW0ORl7mZO8wIWkgtq-yzjQ, cron: 1,2 * * * *)
2026-01-05 22:26:44 +09:00

105 lines
2.6 KiB
JavaScript

import cron from "node-cron";
import pool from "../lib/db.js";
import { syncNewVideos } from "./youtube-bot.js";
// 봇별 스케줄러 인스턴스 저장
const schedulers = new Map();
/**
* 개별 봇 스케줄 등록
*/
export function registerBot(botId, intervalMinutes = 2, cronExpression = null) {
// 기존 스케줄이 있으면 제거
unregisterBot(botId);
// cron 표현식: 지정된 표현식 사용, 없으면 기본값 생성
const expression = cronExpression || `1-59/${intervalMinutes} * * * *`;
const task = cron.schedule(expression, async () => {
console.log(`[Bot ${botId}] 동기화 시작...`);
try {
const result = await syncNewVideos(botId);
console.log(`[Bot ${botId}] 동기화 완료: ${result.addedCount}개 추가`);
} catch (error) {
console.error(`[Bot ${botId}] 동기화 오류:`, error.message);
}
});
schedulers.set(botId, task);
console.log(`[Bot ${botId}] 스케줄 등록됨 (cron: ${expression})`);
}
/**
* 개별 봇 스케줄 해제
*/
export function unregisterBot(botId) {
if (schedulers.has(botId)) {
schedulers.get(botId).stop();
schedulers.delete(botId);
console.log(`[Bot ${botId}] 스케줄 해제됨`);
}
}
/**
* 서버 시작 시 실행 중인 봇들 스케줄 등록
*/
export async function initScheduler() {
try {
const [bots] = await pool.query(
"SELECT id, check_interval, cron_expression FROM bots WHERE status = 'running'"
);
for (const bot of bots) {
registerBot(bot.id, bot.check_interval, bot.cron_expression);
}
console.log(`[Scheduler] ${bots.length}개 봇 스케줄 등록됨`);
} catch (error) {
console.error("[Scheduler] 초기화 오류:", error);
}
}
/**
* 봇 시작
*/
export async function startBot(botId) {
const [bots] = await pool.query("SELECT * FROM bots WHERE id = ?", [botId]);
if (bots.length === 0) {
throw new Error("봇을 찾을 수 없습니다.");
}
const bot = bots[0];
// 스케줄 등록 (cron_expression 우선 사용)
registerBot(botId, bot.check_interval, bot.cron_expression);
// 상태 업데이트
await pool.query(
"UPDATE bots SET status = 'running', error_message = NULL WHERE id = ?",
[botId]
);
// 즉시 1회 실행
try {
await syncNewVideos(botId);
} catch (error) {
console.error(`[Bot ${botId}] 초기 동기화 오류:`, error.message);
}
}
/**
* 봇 정지
*/
export async function stopBot(botId) {
unregisterBot(botId);
await pool.query("UPDATE bots SET status = 'stopped' WHERE id = ?", [botId]);
}
export default {
initScheduler,
registerBot,
unregisterBot,
startBot,
stopBot,
};