use apprise for better notification & fix callback bug & improve log

This commit is contained in:
lyc8503 committed 2024-05-20 14:18:08 +08:00
1 parent d827a7059e
commit 0eb03ebfff
5 files changed
+207 -161

No files matched your search

+16 -114
View File
@@ -58,6 +58,20 @@ const workerConfig = {
timeout: 5000,
},
],
notification: {
// [Optional] apprise API server URL
// if not specified, no notification will be sent
appriseApiServer: "https://apprise.example.com/notify",
// [Optional] recipient URL for apprise, refer to https://github.com/caronc/apprise
// if not specified, no notification will be sent
recipientUrl: "tgram://bottoken/ChatID",
// [Optional] timezone used in notification messages, default to "Etc/GMT"
timeZone: "Asia/Shanghai",
// [Optional] grace period in minutes before sending a notification
// notification will be sent only if the monitor is down for N continuous checks after the initial failure
// if not specified, notification will be sent immediately
gracePeriod: 5,
},
callbacks: {
onStatusChange: async (
env: any,
@@ -70,8 +84,8 @@ const workerConfig = {
// This callback will be called when there's a status change for any monitor
// Write any Typescript code here
// By default, this sends Bark and Telegram notification on every status change if you setup Cloudflare env variables correctly.
await notify(env, monitor, isUp, timeIncidentStart, timeNow, reason)
// This will not follow the grace period settings and will be called immediately when the status changes
// You need to handle the grace period manually if you want to implement it
},
onIncident: async (
env: any,
@@ -86,117 +100,5 @@ const workerConfig = {
},
}
// Below is code for sending Telegram & Bark notification
// You can safely ignore them
const escapeMarkdown = (text: string) => {
return text.replace(/[_*[\](){}~`>#+\-=|.!\\]/g, '\\$&');
};
async function notify(
env: any,
monitor: any,
isUp: boolean,
timeIncidentStart: number,
timeNow: number,
reason: string,
) {
const dateFormatter = new Intl.DateTimeFormat('en-US', {
month: 'numeric',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
hour12: false,
timeZone: 'Asia/Shanghai',
});
let downtimeDuration = Math.round((timeNow - timeIncidentStart) / 60);
const timeIncidentStartFormatted = dateFormatter.format(new Date(timeIncidentStart * 1000));
let statusText = isUp
? `The service is up again after being down for ${downtimeDuration} minutes.`
: `Service became unavailable at ${timeIncidentStartFormatted}. Issue: ${reason || 'unspecified'}`;
console.log('Notifying: ', monitor.name, statusText);
if (env.BARK_SERVER && env.BARK_DEVICE_KEY) {
try {
let title = isUp ? `✅ ${monitor.name} is up again!` : `🔴 ${monitor.name} is currently down.`;
await sendBarkNotification(env, monitor, title, statusText);
} catch (error) {
console.error('Error sending Bark notification:', error);
}
}
if (env.SECRET_TELEGRAM_CHAT_ID && env.SECRET_TELEGRAM_API_TOKEN) {
try {
let operationalLabel = isUp ? 'Up' : 'Down';
let statusEmoji = isUp ? '✅' : '🔴';
let telegramText = `*${escapeMarkdown(
monitor.name,
)}* is currently *${operationalLabel}*\n${statusEmoji} ${escapeMarkdown(statusText)}`;
await notifyTelegram(env, monitor, isUp, telegramText);
} catch (error) {
console.error('Error sending Telegram notification:', error);
}
}
}
export async function notifyTelegram(env: any, monitor: any, operational: boolean, text: string) {
const chatId = env.SECRET_TELEGRAM_CHAT_ID;
const apiToken = env.SECRET_TELEGRAM_API_TOKEN;
const payload = new URLSearchParams({
chat_id: chatId,
parse_mode: 'MarkdownV2',
text: text,
});
try {
const response = await fetch(`https://api.telegram.org/bot${apiToken}/sendMessage`, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: payload.toString(),
});
if (!response.ok) {
console.error(
`Failed to send Telegram notification "${text}", ${response.status} ${response.statusText
} ${await response.text()}`,
);
}
} catch (error) {
console.error('Error sending Telegram notification:', error);
}
}
async function sendBarkNotification(env: any, monitor: any, title: string, body: string, group: string = '') {
const barkServer = env.BARK_SERVER;
const barkDeviceKey = env.BARK_DEVICE_KEY;
const barkUrl = `${barkServer}/push`;
const data = {
title: title,
body: body,
group: group,
url: monitor.url,
device_key: barkDeviceKey,
};
const response = await fetch(barkUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (response.ok) {
console.log('Bark notification sent successfully.');
} else {
const respText = await response.text();
console.error('Failed to send Bark notification:', response.status, response.statusText, respText);
}
}
// Don't forget this, otherwise compilation fails.
export { pageConfig, workerConfig }