Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

slack events api triggers multiple times by one message

I'm using the Slack API to get a link from a Slack workspace. It works except when a message is posted, it triggers more then once. Everytime. Here is the code I have:

exports.slack = (req , res) => {    
var message = req.body;

if (message.challenge) {
     res.send(message.challenge);

} else if (message.event.type == 'message_received') {
    if (message.event.text.includes('<')) {
        // Link
        console.log('NEW LINK');

        var link = message.event.text.slice(1, -1); 

        getArticleInfo(link, (error, body) => {
            if (error) 
                console.error(error);
            else {
                newArticleToDB(body , link, req);
            }
        });  
    }
  } 
}

Everytime a new message is posted I get a 'NEW LINK' log multiple times. Any ideas where to look for this issue?

Thanks.

like image 624
olli208 Avatar asked Jun 06 '18 08:06

olli208


2 Answers

I added res.sendStatus(200) and now everything works as expected. Here's the code:

exports.slack = (req , res) => {    
var message = req.body;
res.sendStatus(200);

if (message.challenge) {
    res.send(message.challenge);

} else if (message.event.type == 'message' && message.event.subtype != 'message_changed') {
    if (message.event.text && message.event.text.includes('<')) {
        // Link
        console.log('NEW LINK');

        var link = message.event.text.slice(1, -1); 

        getArticleInfo(link, (error, body) => {
            if (error) 
                console.error(error);
            else {
                newArticleToDB(body , link, req);
            }
        });  
    }
}
like image 200
olli208 Avatar answered Oct 12 '22 09:10

olli208


I had the issue, thank for @taylor-singletary suggestion. I had to print

console.log('Request Headers::: ', JSON.stringify(req.headers));

to look for

"x-slack-retry-num":"1"

To get header value, simply refer to this question: How to extract request http headers from a request using NodeJS connect

like image 45
vanduc1102 Avatar answered Oct 12 '22 09:10

vanduc1102