Skip to content

Commit

Permalink
sendSlackMessage.js: debounce messages
Browse files Browse the repository at this point in the history
Debounce a message if it was already sent in the last 24 hours
  • Loading branch information
thypon committed May 15, 2024
1 parent 712d5c4 commit f41b4db
Showing 1 changed file with 47 additions and 2 deletions.
49 changes: 47 additions & 2 deletions src/sendSlackMessage.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,22 @@
async function findChannelId (web, name) {
let cursor = null

while (true) {
const r = await web.conversations.list({ cursor })
const f = r.channels.find(c => c.name === name || c.name === name.substring(1))

if (f) {
return f.id
}

if (!r.response_metadata.next_cursor) {
throw new Error('channel not found')
}

cursor = r.response_metadata.next_cursor
}
}

// send markdown message to slack channel
export default async function sendSlackMessage ({
token = null,
Expand All @@ -22,14 +41,21 @@ export default async function sendSlackMessage ({

if (debug) { console.log(`token.length: ${token.length}, channel: ${channel}, message: ${message}`) }

const { WebClient } = await import('@slack/web-api')
const { markdownToBlocks } = await import('@tryfabric/mack')
const { WebClient } = await import('@slack/web-api')

const web = new WebClient(token)
let blocks = await markdownToBlocks(message)

// calculate the sha256 hash of the message
const crypto = await import('crypto')
const hash = crypto.createHash('sha256')
hash.update(message)
const hashHex = hash.digest('hex')

if (debug) { console.log(blocks) }

// slack blocks have a limit of 50 blocks, remove the last blocks if there are more
if (blocks.length > 50) {
blocks = blocks.slice(0, 49)
blocks.push({
Expand All @@ -41,11 +67,30 @@ export default async function sendSlackMessage ({
})
}

// get the channel id
const channelId = await findChannelId(web, channel)

// get last 50 messages from the channel, in the last day
const history = await web.conversations.history({
channel: channelId,
limit: 50,
oldest: Date.now() / 1000 - 60 * 60 * 24 // a day ago
})

// debounce messages if the same message was sent in the last day
if (history.messages.some(m => m.metadata?.event_type === hashHex)) {
throw new Error('debounce message')
}

const metadata = { event_type: hashHex, event_payload: { } }

// send the message
const result = await web.chat.postMessage({
username,
text: `${username} alert`,
channel,
blocks
blocks,
metadata
})

if (debug) { console.log(`result: ${JSON.stringify(result)}`) }
Expand Down

0 comments on commit f41b4db

Please sign in to comment.