Skip to content

Instantly share code, notes, and snippets.

@v-stickykeys
Last active May 4, 2021 19:12
Show Gist options
  • Save v-stickykeys/ba520491be3a5e920186d36db6e78625 to your computer and use it in GitHub Desktop.
Save v-stickykeys/ba520491be3a5e920186d36db6e78625 to your computer and use it in GitHub Desktop.
discordWebhookNotifier.js
const https = require('https')
async function main() {
const embeds = [
{
title: 'Test Title',
description: 'This is a test description.',
color: 16776960,
fields: [
{
name: 'Test Field Name: Color',
value: 'Test Field Value: Yellow',
}
],
},
]
const username = 'discord-webhook-test-notifier'
const retryDelayMs = 5000
console.log('Sending to Discord...')
sendNotification(embeds, username, retryDelayMs)
}
/**
* Sends notification to a Discord channel
* @param embeds {object}
* @param username {string}
* @param retryDelayMs {number} Optional. Amount of time to delay before a retry. -1 means do not retry and is the default.
*/
function sendNotification(embeds, username, retryDelayMs = -1) {
const url = process.env.DISCORD_WEBHOOK_URL
const options = {
method: 'POST',
headers: {
"Content-Type": "application/json"
}
}
const data = { embeds, username }
const req = https.request(url, options, (res) => {
console.log(`Notification request status code: ${res.statusCode}`)
if (res.statusCode == 502 && retryDelayMs > -1) {
console.log(`Retrying after ${retryDelayMs} milliseconds...`)
setTimeout(() => {
sendNotification(embeds, username)
}, retryDelayMs)
} else {
console.log('Not retrying')
}
})
req.on('error', console.error)
req.write(JSON.stringify(data))
req.end()
}
main().then(() => {
console.log('Main function finished running.')
}).catch((err) => {
console.error('Exiting. Caught error:', err)
process.exit(1)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment