From 01a3caf0c92ce322b06a28c89f3472b6332762a5 Mon Sep 17 00:00:00 2001 From: thoverik Date: Tue, 22 Mar 2022 21:14:33 +0700 Subject: [PATCH] override slack message --- server/model/monitor.js | 23 ++++++++++++++++++++--- server/notification-providers/slack.js | 8 +++++++- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/server/model/monitor.js b/server/model/monitor.js index 59ee9202c..43da1c630 100644 --- a/server/model/monitor.js +++ b/server/model/monitor.js @@ -14,6 +14,7 @@ const { Notification } = require('../notification') const { demoMode } = require('../config') const version = require('../../package.json').version const apicache = require('../modules/apicache') +const moment = require('moment') /** * status: @@ -664,17 +665,24 @@ class Monitor extends BeanModel { const notificationList = await Monitor.getNotificationList(monitor) let text + let message if (bean.status === UP) { text = '✅ Up' + const heartbeat = await Monitor.getPreviousHeartbeatByStatus(monitor, DOWN) + message = `${text}: ${monitor.name} ( ${monitor.url} ).` + if (heartbeat) { + const diff = moment(bean.time).diff(moment(heartbeat.time)) + const duration = moment.utc(diff).format('HH:mm:ss.SSS') + message += ` It was down for ${duration}.` + } } else { text = '🔴 Down' + message = `${text}: ${monitor.name} ( ${monitor.url} ). Reason: ${bean.msg}.` } - const msg = `[${monitor.name}] [${text}] ${bean.msg}` - for (const notification of notificationList) { try { - await Notification.send(JSON.parse(notification.config), msg, await monitor.toJSON(), bean.toJSON()) + await Notification.send(JSON.parse(notification.config), message, await monitor.toJSON(), bean.toJSON()) } catch (e) { console.error('Cannot send notification to ' + notification.name) console.log(e) @@ -754,6 +762,15 @@ class Monitor extends BeanModel { monitorID ]) } + + static async getPreviousHeartbeatByStatus (monitorID, status = 0) { + return await R.getRow(` + SELECT status, time FROM heartbeat + WHERE id = (select MAX(id) from heartbeat where monitor_id = ? and status = ?) + `, [ + monitorID, status + ]) + } } module.exports = Monitor diff --git a/server/notification-providers/slack.js b/server/notification-providers/slack.js index b4dad6fe3..bdede8abb 100644 --- a/server/notification-providers/slack.js +++ b/server/notification-providers/slack.js @@ -86,7 +86,13 @@ class Slack extends NotificationProvider { }], }); } - + // overide slack message + data = { + "channel": notification.slackchannel, + "icon_emoji": notification.slackiconemo, + "username": notification.slackusername, + text: msg + } await axios.post(notification.slackwebhookURL, data); return okMsg; } catch (error) {