Slack API & Webhooks
Slack API & Webhooks Slack provides several integration points: Incoming Webhooks (push messages), Slash Commands, Events API (receive events), Web API (full pr…
Slack API & Webhooks
Slack provides several integration points: Incoming Webhooks (push messages), Slash Commands, Events API (receive events), Web API (full programmatic control), and Socket Mode (no public URL needed).
Incoming Webhooks
The simplest way to post messages to Slack. Create a Slack App, enable Incoming Webhooks, and get a URL to POST to.
# Post a simple message
curl -X POST https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXX \
-H 'Content-type: application/json' \
--data '{"text": "Hello from my app!"}'// Node.js example
async function notifySlack(message: string) {
await fetch(process.env.SLACK_WEBHOOK_URL!, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: message,
// Use blocks for rich formatting
blocks: [
{
type: 'section',
text: { type: 'mrkdwn', text: `*Alert:* ${message}` }
}
]
})
})
}Block Kit — Rich Messages
Block Kit is Slack's UI framework for building rich, interactive messages. Blocks replace plain text for anything beyond simple notifications.
{
"blocks": [
{
"type": "header",
"text": { "type": "plain_text", "text": "Deployment Complete" }
},
{
"type": "section",
"fields": [
{ "type": "mrkdwn", "text": "*Environment:*\nProduction" },
{ "type": "mrkdwn", "text": "*Status:*\n:white_check_mark: Success" }
]
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": { "type": "plain_text", "text": "View Logs" },
"url": "https://app.example.com/logs",
"style": "primary"
}
]
}
]
}Web API
import { WebClient } from '@slack/web-api'
const slack = new WebClient(process.env.SLACK_BOT_TOKEN)
// Post a message
await slack.chat.postMessage({
channel: '#deployments',
text: 'Build passed!',
blocks: [...],
})
// Update an existing message
await slack.chat.update({
channel: 'C1234567890',
ts: '1234567890.123456', // message timestamp = unique ID
text: 'Updated message',
})
// Upload a file
await slack.filesUploadV2({
channel_id: 'C1234567890',
filename: 'report.csv',
content: csvData,
})
// Get channel list
const { channels } = await slack.conversations.list({ types: 'public_channel' })
// Lookup user by email
const { user } = await slack.users.lookupByEmail({ email: 'user@example.com' })Slash Commands
// Express handler for /deploy slash command
// Slack sends a POST with application/x-www-form-urlencoded
app.post('/slack/commands/deploy', express.urlencoded({ extended: true }), async (req, res) => {
const { text, user_id, response_url } = req.body
// Respond immediately (Slack times out at 3s)
res.json({ text: 'Deploying...' })
// Do async work, then use response_url to post follow-up
await deploy(text)
await fetch(response_url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: `Deploy of ${text} complete!` })
})
})