We're using a lambda function (node js) to send a message into our slack channel which works. However, when aws is getting a new line its in the format \n. JSON.stringify then encodes this into \\n - and message in slack is like "this is \n a new line". I already tried to replace \\n by \n but this wont work (no msg posted into slack). If i'm checking the console output its:
{"text":"\"This is a \
new line\""}
So it really replaces it with a new line. But what I actually need is a replacement from "This is a \\n new line" into "This is a \n newline" where \n is considered as text so the API of slack is aware of it...??
req.write( JSON.stringify({text: JSON.stringify(rec.Sns.Message, null, ' ')}).replace('\\n', '\n') );
As requested more information - its a webhook in Slack, yes :)
To be honest - i'm a bit lost as I have no idea how to debug directly in AWS. I just assume i have something like this:
console.log( JSON.stringify({text: JSON.stringify("Thats a new \n line", null, ' ')}) );
So i'm ending up with \\n in the console. Then I tried
console.log( JSON.stringify({text: JSON.stringify("Thats a new \n line", null, ' ')}).replace("\\n", "\n") );
Which actually works but then the console output is
Thats a new
line
which makes sense but breaks my API call. So I have no idea how to end up with This is a new \n line encoding..
Maybe it makes sense to post the full lambda function:
console.log('Loading function');
const https = require('https');
const url = require('url');
const slack_url = 'https://hooks.slack.cosm/etc';
const slack_req_opts = url.parse(slack_url);
slack_req_opts.method = 'POST';
slack_req_opts.headers = {'Content-Type': 'application/json'};
exports.handler = function(event, context) {
(event.Records || []).forEach(function (rec) {
if (rec.Sns) {
var req = https.request(slack_req_opts, function (res) {
if (res.statusCode === 200) {
context.succeed('sns posted to slack');
} else {
context.fail('status code: ' + res.statusCode);
}
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
context.fail(e.message);
});
req.write( JSON.stringify({text: JSON.stringify(rec.Sns.Message, null, ' ')}) );
req.end();
}
});
};