Mar 30, 2024

Sending a Slack message with fetch

I like using Slack bots for things like alerts and notifications and have needed this snippet enough to leave it here.

I use slack-block-builder to build the message; writing raw slack blocks is a pain.

const res = await fetch('https://slack.com/api/chat.postMessage', {
method: 'POST',
headers: {
// IMPORTANT! You need to set the charset to utf-8
'Content-Type': 'application/json; charset=utf-8',
// Create an app: https://api.slack.com/apps
Authorization: `Bearer ${process.env.SLACK_BOT_TOKEN}`,
},
body: Message()
// Get this from Slack or the channel URL.
// Be sure to invite the bot to the channel.
.channel('C1234567890')
.blocks(Blocks.Section().text('*Error:* ' + error), Blocks.Divider())
.buildToJSON(),
})
const res = await fetch('https://slack.com/api/chat.postMessage', {
method: 'POST',
headers: {
// IMPORTANT! You need to set the charset to utf-8
'Content-Type': 'application/json; charset=utf-8',
// Create an app: https://api.slack.com/apps
Authorization: `Bearer ${process.env.SLACK_BOT_TOKEN}`,
},
body: Message()
// Get this from Slack or the channel URL.
// Be sure to invite the bot to the channel.
.channel('C1234567890')
.blocks(Blocks.Section().text('*Error:* ' + error), Blocks.Divider())
.buildToJSON(),
})

Thanks for reading! If you want to see future content, you can follow me on Twitter or subscribe to my RSS feed.