Skip to content

Instantly share code, notes, and snippets.

@scripting
Last active July 9, 2022 13:03
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save scripting/2ab9b6f1f38fe699e451 to your computer and use it in GitHub Desktop.
Save scripting/2ab9b6f1f38fe699e451 to your computer and use it in GitHub Desktop.
A tiny JavaScript app that sends a message to your default Slack channel. Can be customized with a name, icon, emoji or sent to a different channel. Runs in Node.js.
var request = require ("request");
var urlWebHook = "https://hooks.slack.com/services/abcdef"; //the URL you get on your "incoming web hooks" page.
function sendToSlack (s, theUsername, theIconUrl, theIconEmoji, theChannel) {
var payload = {
text: s
};
if (theUsername !== undefined) {
payload.username = theUsername;
}
if (theIconUrl !== undefined) {
payload.icon_url = theIconUrl;
}
if (theIconEmoji !== undefined) {
payload.icon_emoji = theIconEmoji;
}
if (theChannel !== undefined) {
payload.channel = theChannel;
}
var theRequest = {
url: urlWebHook,
method: "POST",
json: payload
};
request (theRequest, function (error, response, body) {
if (!error && (response.statusCode == 200)) {
console.log ("sendToSlack: " + s);
}
else {
console.log ("sendToSlack: error, code == " + response.statusCode + ", " + response.body + ".\n");
}
});
}
sendToSlack ("Hello World");
@iholler
Copy link

iholler commented Jan 4, 2018

Wow. Thanks! Had a ton of trouble getting the syntax right for this and getting back a success the past couple tries. Much appreciated sir!

@nwaughachukwuma
Copy link

Hi, am having issues with CORS. Slack is not accepting the payload. I get same issue when call is made from app on firebase hosting
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment