Skip to content

Instantly share code, notes, and snippets.

@23maverick23
Created April 29, 2019 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 23maverick23/f2589cd7867521d019f30d2e4a966859 to your computer and use it in GitHub Desktop.
Save 23maverick23/f2589cd7867521d019f30d2e4a966859 to your computer and use it in GitHub Desktop.
OA: Post message to Slack via webhook
/*
SLACK INCOMING WEBHOOKS REFERENCE
> https://api.slack.com/incoming-webhooks
SLACK MESSAGE ATTACHMENT REFERENCE
> https://api.slack.com/docs/message-attachments
*/
/**
* Post a message to slack after creating a new project.
* @param {Str} type Standard entrance function type.
*/
function afterSaveProject(type) {
// Only proceed if webhook URL paramter has been set
var paramUrl = NSOA.context.getParameter('slack_webhook_development');
if (!paramUrl || paramUrl.length === 0) { return; }
// Only proceed for new records
if (type === 'new') {
var newRec = NSOA.form.getNewRecord();
var prjName = newRec.name;
var prjCustName = newRec.customer_name;
var prjOwnerName = NSOA.record.oaUser(newRec.userid).name;
var prjStartDate = newRec.start_date;
var prjCreated = newRec.created;
var prjBudget = newRec.budget;
var prjBudgetTime = newRec.budget_time;
var startDate = convertTimestampToDate(prjStartDate);
var createdEpoch = convertTimestampToEpoch(prjCreated);
var fields = [
{
title: 'Customer : Project',
value: prjCustName + ' : ' + prjName,
short: false
},
{
title: 'Project owner',
value: prjOwnerName,
short: true
},
{
title: 'Start date',
value: startDate,
short: true
},
{
title: 'Budget (money)',
value: _numberWithCommas(prjBudget),
short: true
},
{
title: 'Budget (hours)',
value: parseInt(prjBudgetTime),
short: true
}
];
var text = 'Beep-beep-boop. A new project has been created!';
var attachment = {
fallback: 'A new project (' + prjCustName + ' : ' + prjName + ') was created.',
color: 'good',
author_name: 'OpenAir AdminBot',
author_icon: 'https://www.pngrepo.com/download/57008/formula-1.png',
fields: fields,
footer: 'OpenAir User Scripting API',
footer_icon: 'https://www.pngrepo.com/download/36709/programming-code-signs.png',
ts: createdEpoch
};
NSOA.meta.log('debug', JSON.stringify(attachment));
var response = postSlackMessage(paramUrl, text, [attachment]);
NSOA.meta.log('debug', JSON.stringify(response));
}
}
/**
* Post a message to slack using a webhook URL.
* @param {Str} text Text to display on message (required).
* @param {Array} attachments Array of attachment objects (optional).
* @return {Obj} An https.post response object.
*/
function postSlackMessage(url, text, attachments) {
// Check that url parameter has a value, otherwise return
url = url || '';
if (!url || url.length === 0) { return null; }
// Check that text parameter has a value, otherwise return
text = text || '';
if (!text || text.length === 0) { return null; }
var body = {
text: text
};
// If attachments param is provided, and it is of type Array (isArray method isn't supported...)
if (attachments && Object.prototype.toString.call(attachments) === '[object Array]') { body.attachments = attachments; }
NSOA.meta.log('debug', 'post.body -> ' + JSON.stringify(body));
var headers = {
'Content-type': 'application/json'
};
var response = NSOA.https.post({
url: url,
body: body,
headers: headers
});
return response;
}
/**
* Converts an OpenAir datetime string to epoch time.
* @param {Str} dateStr An OpenAir datetime string.
* @return {Int} An epoch date value.
*/
function convertTimestampToEpoch(dateStr) {
var d = _convertStringToDateParts(dateStr);
return d.getTime() / 1000;
}
/**
* Converts an OpenAir datetime string to a date string.
* @param {Str} dateStr An OpenAir datetime string.
* @return {Str} A date string value.
*/
function convertTimestampToDate(dateStr) {
var d = _convertStringToDateParts(dateStr);
return d.toDateString();
}
/**
* Converts an OpenAir datetime string into a javascript date object.
* @private
* @param {Str} dateStr Datetime string.
* @return {Obj} Date object.
*/
function _convertStringToDateParts(dateStr) {
var regEx = /^(\d{4})-(\d{2})-(\d{2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
var match = regEx.exec(dateStr);
var year = match[1];
var month = match[2] - 1;
var day = match[3];
var hours = match[4];
var minutes = match[5];
var seconds = match[6];
var d = new Date(year, month, day, hours, minutes, seconds);
// NSOA.meta.log('debug', 'Date from dateStr: ' + dateStr + ' -> ' + d.toString());
return d;
}
/**
* Converts floating number with comma separaters for thousands.
* @private
* @param {Float} num A floating number.
* @return {Float} A floating number, with commas.
*/
function _numberWithCommas(num) {
var regEx = /\B(?=(\d{3})+(?!\d))/g;
return num.toString().replace(regEx, ',');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment