Outbound Calling — Post a Slack Message

In this code sample, the NSOA.https.post function is used to post a message on Slack using a webhook URL. An object is created with url, headers and body properties. The body is defined, including any attachments, and the headers property is used to specify the content type. The object is then passed to the NSOA.https.post function and the response returned.

          /**
 * 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;
} 

        

See also: