mirror of
https://github.com/Nezumi-2711/cloudflare-gateway-pihole-scripts.git
synced 2026-09-22 13:38:37 +00:00
@@ -19,6 +19,53 @@ if (!globalThis.fetch) {
|
||||
globalThis.fetch = (await import("node-fetch")).default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to a Discord-compatible webhook.
|
||||
* @param {url|string} url The webhook URL.
|
||||
* @param {string} message The message to be sent.
|
||||
* @returns {Promise}
|
||||
*/
|
||||
async function sendMessageToWebhook(url, message) {
|
||||
// Create the payload object with the message
|
||||
const payload = { content: message };
|
||||
|
||||
// Send a POST request to the webhook url with the payload as JSON
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
// Check if the request was successful
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! Status: ${response.status}`);
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error sending message to webhook:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a CGPS notification to a Discord-compatible webhook.
|
||||
* Automatically checks if the webhook URL exists.
|
||||
* @param {string} msg The message to be sent.
|
||||
* @returns {Promise}
|
||||
*/
|
||||
export async function notifyWebhook(msg) {
|
||||
// Check if the webhook URL exists
|
||||
const webhook_url = process.env.DISCORD_WEBHOOK_URL;
|
||||
|
||||
if (webhook_url || !webhook_url.startsWith('http')) {
|
||||
// Send the message to the webhook
|
||||
await sendMessageToWebhook(webhook_url, `CGPS: ${msg}`);
|
||||
}
|
||||
// Not logging the lack of a webhook URL since it's not a feature everyone would use
|
||||
}
|
||||
|
||||
/**
|
||||
* Fires request to the specified URL.
|
||||
* @param {string} url The URL to which the request will be fired.
|
||||
@@ -53,6 +100,8 @@ const request = async (url, options) => {
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
// Send a message to the Discord webhook if it exists
|
||||
await notifyWebhook(`An HTTP error has occurred (${response.status}) while making a web request. Please check the logs for further details.`);
|
||||
throw new Error(`HTTP error! Status: ${response.status}`);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user