import { promises as fs } from 'fs'; import path from 'path'; import type { MonitorResult, SilverBaselineAlert } from '../types/index.js'; // 加载环境变量 import 'dotenv/config'; /** * 告警服务 - 提供多种告警方式 */ export class AlertService { private logFilePath: string; constructor(logDir: string = './logs') { this.logFilePath = path.join(logDir, 'alerts.log'); } /** * 初始化日志目录 */ async init(): Promise { try { await fs.mkdir(path.dirname(this.logFilePath), { recursive: true }); } catch (error) { console.error('创建日志目录失败:', error); throw error; } } /** * 控制台告警 */ consoleAlert(result: MonitorResult): void { console.log('\n' + '='.repeat(60)); console.log('🚨 价格变化告警!'); console.log('='.repeat(60)); console.log(`时间: ${new Date(result.timestamp).toLocaleString('zh-CN')}`); console.log(`变化类型: ${result.changeType === 'RISE' ? '📈 上涨' : '📉 下跌'}`); console.log(`美白银: ${result.usSilver}`); console.log(`伦敦银: ${result.londonSilver}`); console.log(`当前价差: ${result.currentSpread.toFixed(3)}`); console.log(`前次价差: ${result.prevSpread.toFixed(3)}`); console.log('='.repeat(60) + '\n'); } /** * 文件日志告警 */ async fileAlert(result: MonitorResult): Promise { try { const logEntry = { timestamp: result.timestamp, changeType: result.changeType, usSilver: result.usSilver, londonSilver: result.londonSilver, currentSpread: result.currentSpread, prevSpread: result.prevSpread }; const logLine = JSON.stringify(logEntry) + '\n'; await fs.appendFile(this.logFilePath, logLine, 'utf-8'); console.log('告警已记录到文件:', this.logFilePath); } catch (error) { console.error('写入告警日志失败:', error); } } /** * Webhook 告警(可扩展用于企业微信、钉钉等) */ async webhookAlert(result: MonitorResult, webhookUrl: string): Promise { try { const message = { msg_type: 'text', content: { text: `🔔 价格变化告警\n⏰ 时间: ${new Date(result.timestamp).toLocaleString('zh-CN')}\n📊 变化类型: ${result.changeType === 'RISE' ? '📈 上涨' : '📉 下跌'}\n💰 美白银: ${result.usSilver}\n💷 伦敦银: ${result.londonSilver}\n📉 价差: ${result.currentSpread.toFixed(3)}` } }; const response = await fetch(webhookUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(message) }); const responseText = await response.text(); if (response.ok) { console.log('Webhook 告警发送成功'); } else { console.error('Webhook 告警发送失败:'); console.error(' 状态码:', response.status, response.statusText); console.error(' 响应:', responseText); } } catch (error: any) { console.error('Webhook 告警出错:', error.message); } } /** * 飞书告警 - 使用飞书卡片消息格式 */ async feishuAlert(result: MonitorResult, webhookUrl: string): Promise { try { const message = { msg_type: 'interactive', card: { header: { title: { tag: 'plain_text', content: '🔔 价格变化告警' }, template: 'red' }, elements: [ { tag: 'div', text: { tag: 'lark_md', content: `**⏰ 时间**\n${new Date(result.timestamp).toLocaleString('zh-CN')}\n\n` + `**📊 变化类型**\n${result.changeType === 'RISE' ? '📈 上涨' : '📉 下跌'}\n\n` + `**💰 价格信息**\n` + `• 美白银: ${result.usSilver}\n` + `• 伦敦银: ${result.londonSilver}\n` + `• 当前价差: ${result.currentSpread.toFixed(3)}\n` + `• 前次价差: ${result.prevSpread.toFixed(3)}` } } ] } }; const response = await fetch(webhookUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(message) }); const responseText = await response.text(); if (response.ok) { console.log('飞书告警发送成功'); } else { console.error('飞书告警发送失败:'); console.error(' 状态码:', response.status, response.statusText); console.error(' 响应:', responseText); } } catch (error: any) { console.error('飞书告警出错:', error.message); } } /** * 发送飞书执行情况汇总(每2小时) */ async sendFeishuSummary(webhookUrl: string, summary: { runCount: number; totalPrices: number; totalChanges: number; riseCount: number; fallCount: number; currentPrice?: { usSilver: string; londonSilver: string; spread: number }; recentChanges: Array<{ timestamp: number; changeType: string; currentSpread: number }>; }): Promise { try { const now = new Date(); const timeRange = `${now.getHours() - 2}:00 - ${now.getHours()}:00`; let recentChangesText = '暂无变化'; if (summary.recentChanges.length > 0) { recentChangesText = summary.recentChanges.map(change => { const time = new Date(change.timestamp).toLocaleTimeString('zh-CN'); const icon = change.changeType === 'RISE' ? '📈' : '📉'; return `${icon} ${time} - 价差: ${change.currentSpread.toFixed(3)}`; }).join('\n'); } const message = { msg_type: 'interactive', card: { header: { title: { tag: 'plain_text', content: '📊 每2小时监控报告' }, template: 'blue' }, elements: [ { tag: 'div', text: { tag: 'lark_md', content: `**⏰ 统计时段**\n${timeRange}\n\n` + `**📈 运行统计**\n` + `• 运行次数: ${summary.runCount} 次\n` + `• 价格记录: ${summary.totalPrices} 条\n` + `• 变化次数: ${summary.totalChanges} 次\n` + `• 上涨信号: ${summary.riseCount} 次\n` + `• 下跌信号: ${summary.fallCount} 次\n\n` + (summary.currentPrice ? `**💰 当前价格**\n` + `• 美白银: ${summary.currentPrice.usSilver}\n` + `• 伦敦银: ${summary.currentPrice.londonSilver}\n` + `• 当前价差: ${summary.currentPrice.spread.toFixed(3)}\n\n` : '') + `**📋 最近变化**\n${recentChangesText}` } } ] } }; const response = await fetch(webhookUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(message) }); const responseText = await response.text(); if (response.ok) { console.log('飞书汇总报告发送成功'); } else { console.error('飞书汇总报告发送失败:'); console.error(' 状态码:', response.status, response.statusText); console.error(' 响应:', responseText); } } catch (error: any) { console.error('发送飞书汇总报告出错:', error.message); } } /** * 发送白银基线告警到飞书 */ async sendSilverBaselineAlert(webhookUrl: string, alert: SilverBaselineAlert): Promise { try { const alertTypeText = alert.type === 'RISE' ? '📈 上涨' : '📉 下跌'; const alertColor = alert.type === 'RISE' ? 'green' : 'red'; const message = { msg_type: 'interactive', card: { header: { title: { tag: 'plain_text', content: `🔔 白银价格${alertTypeText}告警` }, template: alertColor }, elements: [ { tag: 'div', text: { tag: 'lark_md', content: `**⏰ 时间**\n${new Date(alert.timestamp).toLocaleString('zh-CN')}\n\n` + `**💰 价格信息**\n` + `• 当前价格: ${alert.currentPrice.toFixed(3)}\n` + `• 基线价格: ${alert.baseline.toFixed(3)}\n` + `• 价格变化: ${alert.change > 0 ? '+' : ''}${alert.change.toFixed(3)}\n` + `• 变化百分比: ${alert.changePercent > 0 ? '+' : ''}${alert.changePercent.toFixed(2)}%\n\n` + `**📊 告警说明**\n` + `价格${alert.type === 'RISE' ? '上涨' : '下跌'}超过阈值,基线已自动更新为当前价格` } } ] } }; const response = await fetch(webhookUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(message) }); const responseText = await response.text(); if (response.ok) { console.log('白银基线告警发送成功'); } else { console.error('白银基线告警发送失败:'); console.error(' 状态码:', response.status, response.statusText); console.error(' 响应:', responseText); } } catch (error: any) { console.error('发送白银基线告警出错:', error.message); } } /** * 综合告警(同时使用多种方式) */ async alert(result: MonitorResult, options: { console?: boolean; file?: boolean; webhook?: string; feishu?: string; } = {}): Promise { const { console: enableConsole = true, file: enableFile = true, webhook, feishu } = options; if (enableConsole) { this.consoleAlert(result); } if (enableFile) { await this.fileAlert(result); } if (webhook) { await this.webhookAlert(result, webhook); } if (feishu) { await this.feishuAlert(result, feishu); } } } /** * 创建默认的告警回调函数 */ export function createAlertCallback(alertService: AlertService): (result: MonitorResult) => Promise { return async (result: MonitorResult) => { await alertService.alert(result, { console: true, file: true, webhook: process.env.WEBHOOK_URL // 从环境变量读取 webhook 地址 }); }; }