Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

attachment issues

Jack62
Giga Guru

I have tried logging this a few times but I am getting marked as spam. Can anyone confirm if the below script in my business rule should send an attachment through Rest? once confirmed I will send the error I am seeing in the logs.

 

var parser = new JSONParser();
var parsed = parser.parse(responseBody);
var targetRec = parsed.result;
var attachmentCount = sendAttachments(current.getTableName(),
current.sys_id, targetRec.sys_id);
if (attachmentCount != "none") {
attachmentMsg = " Attachments successfully sent: " +
attachmentCount[0].toString() + ". Attachments failed to be sent: " +
attachmentCount[1].toString();
} else {
attachmentMsg = " Record had no attachments to send.";
}
5 REPLIES 5

Amit Pandey
Kilo Sage

Hi @Jack62 

 

Can you help me with the screenshot of REST Message? Alternatively, you can try this-

 

 

var incidentSysId = current.sys_id.toString();
var attachmentRecord = new GlideRecord('sys_attachment');
 attachmentRecord.addQuery('table_sys_id', incidentSysId);
        attachmentRecord.query();
        if (attachmentRecord.next()) {
            var attachmentSysId = attachmentRecord.sys_id.toString();

            // Prepare RESTMessageV2 for the API call
            var restMessage = new sn_ws.RESTMessageV2();
            restMessage.setHttpMethod('post');
            restMessage.setEndpoint('YOUR_ENDPOINT_URL'); // Set your REST endpoint URL
            restMessage.setRequestHeader("Content-Type", "application/json");
            // Additional headers like Authorization as needed
            // restMessage.setRequestHeader("Authorization", "Bearer YOUR_ACCESS_TOKEN");

            var requestBody = {
                "incidentSysId": incidentSysId,
                "attachmentSysId": attachmentSysId
                // Populate as per the API requirements
            };

            restMessage.setRequestBody(JSON.stringify(requestBody));

            try {
                var response = restMessage.execute();
                var responseBody = response.getBody();
                var httpStatus = response.getStatusCode();
                // Handle the response, parse JSON, etc.
                gs.info("REST call successful: " + responseBody);
            } catch (ex) {
                var errorMsg = ex.getMessage();
                gs.error("REST call error: " + errorMsg);
            }
        }
    }

 

 

Sorry for the late reply, this was paused to work on a priority. So we are now getting a 200 response sending to the other side but the logs are showing and empty response body. my BR is below, can anyone assist with the issue? We need to pull the end point each time before we post the attachment back.

 

(function executeRule(current, previous /*null when async*/) {
gs.log('Ensatt running');
var corrID = '';
    var ensChk = new GlideRecord(current.table_name);
    ensChk.addQuery('sys_id',current.table_sys_id);
    ensChk.query();
    if(ensChk.next()){
        corrID = ensChk.correlation_id;
        gs.log('Ensatt corr ' + corrID);
    }
    var corrIDchk = corrID.search('e-CS');
    if(corrIDchk != '-1'){
        gs.log('Ensatt found e-CS');

var r = new sn_ws.RESTMessageV2('an integration', 'Get Attachment URL');
           
            r.setStringParameterNoEscape('ticketno',corrID);
            var responser = r.execute();
            var responseBodyr = responser.getBody();
            var httpStatusr = responser.getStatusCode();
            gs.log('Ensatt GET responsebody: ' + responseBodyr );
            gs.log('Ensatt status' + httpStatusr);

var parsed = JSON.parse(responseBodyr);
            for (var key in parsed) {
                if (parsed.hasOwnProperty(key)){
                    var parsed_object = parsed[key];
                   
                    var body = parsed_object.body;
                   
                }
            }
            gs.log('ensx ' + body);
            gs.log('ensx att sys ' + current.sys_id);
            gs.log('ensx att type ' + current.content_type);
        var s = new sn_ws.RESTMessageV2('an integration', 'Send attachment');
            s.setRequestHeader('Content-Type',current.content_type);
            s.setEndpoint(body);
            s.setRequestBodyFromAttachment(current.sys_id);
            //s.setStringParameterNoEscape('ticketno',corrID);
            var response = s.execute();
            var responseBody = response.getBody();
            var httpStatus = response.getStatusCode();
            gs.log('Ensatt PUT responsebody: ' + responseBody );
            gs.log('Ensatt PUT status' + httpStatus);


    }

})(current, previous);

 

Hi @Jack62 

 

Can you share the screenshot of the REST Message, you have configured. Also, I need the logs from the script for further debugging-

 

(function executeRule(current, previous /*null when async*/) {
    gs.log('Ensatt running');
    var corrID = '';
    var ensChk = new GlideRecord(current.table_name);
    ensChk.addQuery('sys_id', current.table_sys_id);
    ensChk.query();

    if (ensChk.next()) {
        corrID = ensChk.correlation_id;
        gs.log('Ensatt corr ' + corrID);
    } else {
        gs.log('No record found with sys_id: ' + current.table_sys_id);
        return; // Exit if no record is found
    }

    var corrIDchk = corrID.search('e-CS');
    if (corrIDchk != '-1') {
        gs.log('Ensatt found e-CS');

        var r = new sn_ws.RESTMessageV2('an integration', 'Get Attachment URL');
        r.setStringParameterNoEscape('ticketno', corrID);
        var responser = r.execute();
        var responseBodyr = responser.getBody();
        var httpStatusr = responser.getStatusCode();

        // Log the raw response body for debugging
        gs.log('Ensatt GET raw response body: ' + responseBodyr);
        gs.log('Ensatt GET status: ' + httpStatusr);

        // Check if the response body is not empty and is valid JSON
        if (responseBodyr && responseBodyr !== '') {
            try {
                var parsed = JSON.parse(responseBodyr);
                var body = ''; // Initialize the body variable outside of the loop
                for (var key in parsed) {
                    if (parsed.hasOwnProperty(key)) {
                        var parsed_object = parsed[key];
                        body = parsed_object.body; // Assume 'body' is directly under the parsed object
                        break; // Assuming we only need the first occurrence
                    }
                }

                if (body === '') {
                    gs.log('No attachment URL found in response');
                    return; // Exit if no attachment URL is found
                }

                gs.log('ensx ' + body);
                gs.log('ensx att sys ' + current.sys_id);
                gs.log('ensx att type ' + current.content_type);

                var s = new sn_ws.RESTMessageV2('an integration', 'Send attachment');
                s.setRequestHeader('Content-Type', current.content_type);
                s.setEndpoint(body);
                s.setRequestBodyFromAttachment(current.sys_id);
                var response = s.execute();
                var responseBody = response.getBody();
                var httpStatus = response.getStatusCode();

                gs.log('Ensatt PUT response body: ' + responseBody);
                gs.log('Ensatt PUT status: ' + httpStatus);
            } catch (e) {
                gs.log('Error parsing JSON response: ' + e.toString());
            }
        } else {
            gs.log('Empty or invalid JSON response received');
        }
    } else {
        gs.log('Correlation ID does not contain "e-CS"');
    }
})(current, previous);

Regards,

Amit

Hey, thanks for the above, logs and rest below

Jack62_0-1710920348037.png

The Rest is basic as we are pulling the end point to then send the attachment. in the headers we have the x-api-key.

 

Jack62_2-1710920498866.png