#!/usr/bin/env node /** * CLI: 手动执行监控任务 * * 用法: * node scripts/run-task.js — 执行指定任务 * node scripts/run-task.js --all — 执行所有启用的任务 * node scripts/run-task.js --test-push [chat] — 测试 Telegram 推送 */ require('dotenv').config({ path: require('path').join(__dirname, '..', '.env') }); const db = require('../src/db'); const { runTask } = require('../src/utils/taskRunner'); const { sendTestMessage } = require('../src/utils/telegram'); async function main() { const args = process.argv.slice(2); if (args.length === 0) { console.log(` 用法: node scripts/run-task.js 执行指定任务 node scripts/run-task.js --all 执行所有启用的任务 node scripts/run-task.js --test-push [chat] 测试 TG 推送 node scripts/run-task.js --list 列出所有任务 环境变量: TG_BOT_TOKEN Telegram Bot Token TG_DEFAULT_CHANNEL_ID 默认推送频道 `); process.exit(0); } if (args[0] === '--test-push') { const chatId = args[1] || undefined; console.log('🧪 发送测试推送...'); const result = await sendTestMessage(chatId); console.log(result.ok ? '✅ 推送成功' : `❌ 推送失败: ${result.description}`); process.exit(result.ok ? 0 : 1); } if (args[0] === '--list') { const tasks = db.prepare(` SELECT t.id, t.enabled, t.cron_expr, t.last_run, p.name AS product_name, m.name AS merchant_name FROM monitor_tasks t LEFT JOIN products p ON t.product_id = p.id LEFT JOIN merchants m ON p.merchant_id = m.id ORDER BY t.id `).all(); if (tasks.length === 0) { console.log('暂无任务'); } else { console.log('ID | 状态 | 产品 | 上次运行'); console.log('-'.repeat(70)); for (const t of tasks) { const status = t.enabled ? '✅' : '⏸ '; console.log(`${String(t.id).padEnd(4)}| ${status} | ${(t.merchant_name + ' — ' + t.product_name).padEnd(30)}| ${t.last_run || '-'}`); } } process.exit(0); } if (args[0] === '--all') { const tasks = db.prepare('SELECT id FROM monitor_tasks WHERE enabled = 1').all(); if (tasks.length === 0) { console.log('没有启用的任务'); process.exit(0); } console.log(`🔄 执行 ${tasks.length} 个任务...\n`); for (const task of tasks) { console.log(`── 任务 #${task.id} ──`); const result = await runTask(task.id); console.log(` ${result.message}\n`); } console.log('✅ 全部完成'); process.exit(0); } // 指定 task_id const taskId = parseInt(args[0], 10); if (isNaN(taskId)) { console.error('❌ 无效的 task_id:', args[0]); process.exit(1); } console.log(`🔄 执行任务 #${taskId}...`); const result = await runTask(taskId); console.log(result.message); process.exit(result.success ? 0 : 1); } main().catch(err => { console.error('❌ 致命错误:', err); process.exit(1); });