I have created a unique Slack application that monitors messages sent to a specific channel. When it detects a message, it initiates an event to a URL hosted on my frontend system (Next.js), which then makes a POST request to the backend for a response. Once the response is received, it is sent back to Slack as a message.
Here is the code snippet from the route:
import { WebClient } from '@slack/web-api'
const web = new WebClient(process.env.SLACK_TOKEN)
export async function POST(req: Request) {
const data = await req.json()
console.log(data)
if (data.type === 'url_verification') {
return Response.json({ challenge: data.challenge })
}
if (
!data.event.thread_ts &&
!data.event.parent_user_id &&
data.event.type === 'message' &&
data.type === 'event_callback' &&
data.event.channel === 'C06GGJVRMCK'
) {
const response = await fetch(process.env.AWS_BACKEND_ENDPOINT || '', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: [
{
role: 'user',
content: data.event.text
}
]
})
}
)
const json = await response.json()
await web.chat.postMessage({
text: json.data.content,
thread_ts: data.event.ts,
channel: data.event.channel
})
return new Response(data.challenge, {
status: 200
})
}
return new Response('Ok', {
status: 200
})
}
However, I've noticed that multiple duplicate submissions occur whenever a single message is sent to the channel. This results in several repeated responses from the backend being sent back to Slack. Every message sent triggers approximately 3 to 4 POST requests in the backend, resulting in the delivery of 3 to 4 response messages on Slack.
I am looking for suggestions on how to prevent these multiple POST requests triggered by Slack messages and ensure that only one response is sent for each incoming message.
Any advice or alternative methods to address this issue would be greatly appreciated. Thank you for your help!
Despite trying to send an early response with status 200 'OK', I am still encountering multiple events.
Expected Outcome:
My goal was to implement a solution that effectively prevents multiple POST requests from being triggered by a single Slack message. This would ensure that only one POST request is sent to the backend and one response is sent back to Slack for each message received, eliminating redundancy and enhancing user experience.