trigger slack message in servicenow

ujjwala_678
Tera Contributor

Hi All,

I have this new request to send slack message in servicenow using scheduled job 

Any existing script include I can utilise for this?

How should I fetch data using scheduled job? I am newbie to this integration 

Please feel free to share your thoughts on this. All kinds of suggestions are highly appreciated.

Thank you 

6 REPLIES 6

Rajdeep Ganguly
Mega Guru


Sure, I can guide you on how to send a Slack message from ServiceNow using a scheduled job. Here are the steps:

1. **Create a Slack App and Incoming Webhook:**
- Go to https://api.slack.com/apps and create a new app.
- From the app settings, select "Incoming Webhooks" and activate them.
- Add a new webhook to the workspace where you want to send messages. You will get a Webhook URL which will be used in ServiceNow.

2. **Create a Script Include in ServiceNow:**
- This script will be responsible for sending messages to Slack. Here is a sample script:

javascript
var SlackMessage = Class.create();
SlackMessage.prototype = {
initialize: function() {
},

send: function(webhook_url, message) {
var restMessage = new sn_ws.RESTMessageV2();
restMessage.setHttpMethod('post');
restMessage.setEndpoint(webhook_url);
restMessage.setRequestHeader('Content-Type', 'application/json');
var postBody = {
"text": message
};
restMessage.setRequestBody(JSON.stringify(postBody));
var response = restMessage.execute();
return response.getStatusCode();
},

type: 'SlackMessage'
};


3. **Create a Scheduled Job in ServiceNow:**
- This job will fetch data and send it to Slack. Here is a sample script:

javascript
var job = Class.create();
job.prototype = {
initialize: function() {
},

process: function() {
// Fetch data
var gr = new GlideRecord('table_name'); // replace 'table_name' with your table
gr.query();
while (gr.next()) {
// Prepare message
var message = 'Record: ' + gr.getValue('field_name'); // replace 'field_name' with your field

// Send message to Slack
var sm = new SlackMessage();
sm.send('your_webhook_url', message); // replace 'your_webhook_url' with your Slack Webhook URL
}
},

type: 'job'
};


4. **Schedule the Job:**
- Go to "System Definition > Scheduled Jobs" in ServiceNow.
- Create a new job and select the script you created in the previous step.
- Set the schedule according to your needs.

Please replace the placeholders in the scripts with your actual values. Also, make sure to test everything in a non-production instance first.


nowKB.com

Hi @Rajdeep Ganguly ,

Thank you for your response on this....there is one more thing to do I have to add two buttons just like "Approve" or "Reject" we have on approval records....I want along with the message , script should display those two buttons to users and based on users reponse approve or reject comments need to be added to record.

Any thoughts if you can share on this?

Thank you