Skip to content

Instantly share code, notes, and snippets.

@javatask
Created February 15, 2021 14:16
Show Gist options
  • Save javatask/bfec8a63ab76c55b01b1b07b0f2bcfe4 to your computer and use it in GitHub Desktop.
Save javatask/bfec8a63ab76c55b01b1b07b0f2bcfe4 to your computer and use it in GitHub Desktop.
Usage of Incoming webhooks for Slack
const https = require("https");
const { URL } = require("url");
const webHookUrl = process.env.WEBHOOK_URL || "fakeWebhook";
function publishSlackMessage({ message, webHook }) {
return new Promise(function (resolve) {
const url = new URL(webHook);
const reqOpts = {};
reqOpts.hostname = url.hostname;
reqOpts.path = url.pathname;
reqOpts.method = "POST";
reqOpts.headers = { "Content-Type": "application/json" };
const req = https.request(reqOpts, function (res) {
if (res.statusCode === 200) {
console.log("Published message to channel " + webHook);
} else {
console.log(res.statusCode + " - Error posting to webhook " + webHook);
}
resolve();
});
req.on("error", function (e) {
console.log("Request posting to Slack was invalid:" + e.message);
resolve();
});
req.write(JSON.stringify({ text: message }));
req.end();
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment