2
votes

I implemented this AWS Lambda that receives events from slack and response back to slack a sentence and I want to monitor their answer back to the lambda to verify that the message arrived and posted.

// Lambda handler
exports.handler = (data, context, callback) => {
    switch (data.type) {
        case "url_verification": verify(data, callback); break;
        case "event_callback": process(data.event, callback); break;
        default: callback(null);
    }
};

// Post message to Slack - https://api.slack.com/methods/chat.postMessage
function process(event, callback) {
    // test the message for a match and not a bot
    if (!event.bot_id && /(aws|lambda)/ig.test(event.text)) {
        var text = `<@${event.user}> isn't AWS Lambda awesome?`;
        var message = { 
            token: ACCESS_TOKEN,
            channel: event.channel,
            text: text
        };

        var query = qs.stringify(message); // prepare the querystring
        https.get(`https://slack.com/api/chat.postMessage?${query}`);
    }

    callback(null);
}

I want to know how can I get the response of my HTTPS request (that send to me by slack) back to my lambda?

2

2 Answers

1
votes

If I understood correctly you want to wait for the result of the your get query.

In your code callback is called immediately and lambda finishes its execution. To be able to wait for the response you need to remove callback from its current position in the code and call it after request was performed.

// Post message to Slack - https://api.slack.com/methods/chat.postMessage
function process(event, callback) {
    // test the message for a match and not a bot
    if (!event.bot_id && /(aws|lambda)/ig.test(event.text)) {
        var text = `<@${event.user}> isn't AWS Lambda awesome?`;
        var message = { 
            token: ACCESS_TOKEN,
            channel: event.channel,
            text: text
        };

        var query = qs.stringify(message); // prepare the querystring
        https.get(`https://slack.com/api/chat.postMessage?${query}`, (res, err) => {
            if (err) return callback(err);
            callback(null);
        })
    }

    // callback was here
}
1
votes

If you can, use request/request-promise to save some lines of code.

To get the http response in your Lambda Function you just need to wait for the response before calling the Lambda Callback.

Eg.:

var request = require('request-promise');

exports.handler = (event, context, callback) => {
  request('https://somedomain.com').then((body) => {
    //got the response body
    callback(null, body);
  });
}

It's the same idea if you're using the https module.