bolt-js icon indicating copy to clipboard operation
bolt-js copied to clipboard

Responding HTTP 200 to an event with the bolt sdk

Open 6lick opened this issue 4 years ago • 12 comments

Description

Message listeners are firing multiple times because they are not receiving an HTTP 200 response but ack() cannot be used in the context of event listeners so I am not sure how (or where) I'm supposed to send a 200 to.

What type of issue is this? (place an x in one of the [ ])

  • [ ] bug
  • [ ] enhancement (feature request)
  • [x] question
  • [ ] documentation related
  • [ ] example code related
  • [ ] testing related
  • [ ] discussion

Requirements (place an x in each of the [ ])

  • [x] I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • [x] I've read and agree to the Code of Conduct.
  • [x] I've searched for any related issues and avoided creating a duplicate issue.

6lick avatar Oct 31 '22 18:10 6lick

Hi, @6lick! Thanks so much for submitting this question!

Could you send a snippet of code for your message listener and how you are handling the listener? This will help me troubleshoot your issue further!

hello-ashleyintech avatar Oct 31 '22 18:10 hello-ashleyintech

Yeah sure- it basically just makes external api calls to salesforce logging the message on the corresponding opportunity.

This is the method signature async function syncSlackToDealChannel ({message, say, context}) {...

There's basically no handling of the listener because I don't know how to respond to it- it kicks off a series of external api calls.

6lick avatar Oct 31 '22 18:10 6lick

Basically it looks like this async function syncSlackToDealChannel ({message, say, context}) { someExternalAuthStuff(); parseMsgData(); sendToSalesforce(); }

6lick avatar Oct 31 '22 18:10 6lick

@6lick Thanks for providing additional info!

Whether you are using message listeners via app.event() or app.message() for your app, the handler should terminate on its own and not loop once the function body has been executed - because of this, there should not be a need for an ack() and I would make sure that the logic within your handler is being fully executed to completion.

Since you are using API calls nested within the body, I would examine the body of your message listener handler and if you are not already, use the await keyword to stagger the API calls you are using within the async function and make sure each call resolves before calling the others, as seen briefly in this example from the docs. Based on the pseudocode you provided, it would likely look something like this:

async function syncSlackToDealChannel ({message, say, context}) { 
    await someExternalAuthStuff();
    await parseMsgData();
    await sendToSalesforce();
}

I hope this helps, let me know if you have further questions and feel free to provide additional info and I would be happy to assist!

hello-ashleyintech avatar Oct 31 '22 18:10 hello-ashleyintech

Hmmm ok. I'll post the whole function- warning- its ugly right now

app.message( "", dealActionHandlers.syncSlackToDealChannel)

`async function syncSlackToDealChannel ({message, say, context}) { console.log("***************") console.log('after ack') console.log(message) if (message.text.indexOf('has joined the channel') != -1){ console.log('join message'); return; } let userInfo = await app.client.users.info({user:message.user, token: context.botToken}) console.log(userInfo) // let user = await getSFToken(message.user, context ) if (userInfo.user.is_bot){ console.log('bot message') return } let orgInfo = await mercUtils.getSFDCWebhookBase(context.teamId) console.log('calling ger refresh token') let newToken = await mercUtils.getSFDCTokenwithRefreshToken(message.user, orgInfo.sfdcInstanceUrl, context) let webhookUrl; // console.log(orgInfo) if (orgInfo.isNamespacedInstall) webhookUrl = orgInfo.sfdcInstanceUrl + mercConfig.sfdcPathsNamespaced.writeToCase else webhookUrl = orgInfo.sfdcWebhookUrl + mercConfig.sfdcPaths.writeToCase console.log(webhookUrl)

//get channel name
let channelInfo = await app.client.conversations.info({channel: message.channel, token: context.botToken})
let channelName = channelInfo.channel.name
let dealChannelmd = orgInfo.dealChannels.find(dealmd => dealmd.channelName === channelName)
console.log(dealChannelmd)
let qp;
let isDeal = false;
if(dealChannelmd.dealId){
  isDeal = true;
  qp = `/services/data/v54.0/query?q=SELECT+Id+,+MERC__Primary_Opportunity_Id__c+FROM+MERC__Deal__c+where+id='${dealChannelmd.dealId}'+LIMIT+1`
}
else {
  qp = `/services/data/v54.0/query?q=SELECT+Id+,+MERC__RelatedOpportunity__r.Id+FROM+Case+where+CaseNumber='${dealChannelmd.caseNumber}'+LIMIT+1`
}
let queryPath1 = `/services/data/v54.0/query?q=SELECT+Id+,+MERC__RelatedOpportunity__r.Id+FROM+Case+where+MERC__ThreadId__c='${message.thread_ts}'+LIMIT+1`
let dealIdQ = `/services/data/v54.0/query?q=SELECT+Id+,+MERC__RelatedOpportunity__r.Id+,+MERC__RelatedOpportunity__r.merc__deal__c + FROM+Case+where+CaseNumber='${dealChannelmd.caseNumber}'+LIMIT+1`

console.log(orgInfo.sfdcInstanceUrl + qp)
let uri = orgInfo.sfdcInstanceUrl + `/services/data/v54.0/chatter/feed-elements`;
console.log(message.text)
let oppResp;
let dealResp;
let chatterPost = {
  "body" : {
     "messageSegments" : [
        {
           "type" : "Text",
           "text" : message.text
        },
        {
          "markupType" : "Paragraph",
          "type" : "MarkupBegin"
       },
       {
          "markupType" : "Paragraph",
          "type" : "MarkupEnd"
       },
       {
          "markupType" : "Paragraph",
          "type" : "MarkupBegin"
       },
       {
          "markupType" : "Paragraph",
          "type" : "MarkupEnd"
       },
       {
        "markupType" : "Paragraph",
        "type" : "MarkupBegin"
      },
      {
          "markupType" : "Paragraph",
          "type" : "MarkupEnd"
      }]
      },
  "feedElementType" : "FeedItem",

} if (message.thread_ts){ oppResp = await axios.get(orgInfo.sfdcInstanceUrl + queryPath1, {headers: {"Authorization": Bearer ${newToken}}}) chatterPost.subjectId = oppResp.data.records[0].Id if (message.files){ console.log('calling send file to thread') let cids = await mercUtils.sendFiletoSF(message, newToken, orgInfo.sfdcInstanceUrl, oppResp.data.records[0].Id, context.botToken) chatterPost.capabilities = { "files":{ "items": cids } } } // dealResp = await axios.get(orgInfo.sfdcInstanceUrl + dealIdQ, {headers: {"Authorization": Bearer ${newToken}}})

  console.log('in thread, post to case')
  axios.post(uri , chatterPost ,{headers: {"Authorization": `Bearer ${newToken}`}}).then(function (response) {
  console.log("data written to SFDC");
  })
  .catch(function (error) {
  /*
  if(error.status == '401'){
    getSFDCTokenwithRefreshToken()
  }
  */
 
    console.log(error);
  });
}else{
  console.log('in general, post to opp')
  try{
    oppResp = await axios.get(orgInfo.sfdcInstanceUrl + qp, {headers: {"Authorization": `Bearer ${newToken}`}})
  }catch(e){
    console.log('failed to fetch opp/case info\n')
    console.log(e)
  }
  if (message.files){
    console.log('calling send file to opp')
    let cids = await mercUtils.sendFiletoSF(message, newToken, orgInfo.sfdcInstanceUrl, oppResp.data.records[0].MERC__RelatedOpportunity__r.Id, context.botToken)
    chatterPost.capabilities = {
      "files":{
        "items": cids
     }
    }
  }

  
  if (isDeal){
    chatterPost.subjectId = oppResp.data.records[0].MERC__Primary_Opportunity_Id__c
  }else{
    chatterPost.subjectId = oppResp.data.records[0].MERC__RelatedOpportunity__r.Id
  }
  axios.post(uri , chatterPost,{headers: {"Authorization": `Bearer ${newToken}`}}).then(function (response) {
  console.log("data written to SFDC");
})
.catch(function (error) {
  /*
  if(error.status == '401'){
    getSFDCTokenwithRefreshToken()
  }
  */
 
  console.log(error);
});
}

}`

6lick avatar Oct 31 '22 18:10 6lick

Thanks for sharing your code @6lick! At an initial glance, I'm noticing you are indeed using the await keywords and nothing obvious jumps out to me that might be causing the looping. I am wondering if the message listeners are firing multiple times because you are passing in an empty string, "", as the message you are listening for. Have you tried testing this with a specific message keyword passed in to your listener (ex: hi) to see if it still executes it multiple times?

hello-ashleyintech avatar Oct 31 '22 18:10 hello-ashleyintech

Ill try that... its weird because it seems to randomly fire multiple times- its doesn't happen every time the listener is called

6lick avatar Oct 31 '22 18:10 6lick

https://api.slack.com/apis/connections/events-api#the-events-api__responding-to-events this doc seems to indicate that I need to respond

6lick avatar Oct 31 '22 19:10 6lick

Is there a way I can turn retries off with the bolt sdk?

6lick avatar Oct 31 '22 19:10 6lick

Thanks for linking that resource, @6lick! 🙌 Upon further digging based on what you provided as well as reading other issues, I suspect that because your event handler has a lot of logic to execute in the body, it is timing out and attempting to retry because, as you mentioned above, the Events API under the hood of the Bolt JS events listener is not receiving a 200 HTTP response in the designated time. Sadly, the Bolt JS framework does not currently allow for setting extra headers to mitigate these retries as is suggested in the Event API documentation, and it is also not the recommended approach for Bolt apps, since doing so means that your application will lose all event data if any temporary interruption occurs with your application.

With that being said, I think you could likely do a few things from here to try to work around this this:

  • If possible, you could try to cut back or reduce the logic within your listener's handler function to only what is necessary within the handler - this might help prevent timeouts.
  • If the above does not work or is not a feasible approach for you, we suggest you create your own receiver. A receiver is responsible for handling and parsing any incoming requests from Slack, then sending it to the app, so that the app can add context and pass the request to your listeners. You can find documentation on how to create a receiver here and an example is provided here.

I hope this helps! Thank you for providing the information to allow me to troubleshoot this with you and I'm happy to answer any additional questions as needed!

hello-ashleyintech avatar Oct 31 '22 20:10 hello-ashleyintech

👋 It looks like this issue has been open for 30 days with no activity. We'll mark this as stale for now, and wait 10 days for an update or for further comment before closing this issue out. If you think this issue needs to be prioritized, please comment to get the thread going again! Maintainers also review issues marked as stale on a regular basis and comment or adjust status if the issue needs to be reprioritized.

github-actions[bot] avatar Dec 05 '22 00:12 github-actions[bot]

As this issue has been inactive for more than one month, we will be closing it. Thank you to all the participants! If you would like to raise a related issue, please create a new issue which includes your specific details and references this issue number.

github-actions[bot] avatar Dec 19 '22 00:12 github-actions[bot]