Petru Constantin este fondatorul DeviDevs și a proiectat platforma multi-agent pe care rulează firma, cu guardrails impuse în cod. Exemplele de cod sunt scrise pe documentația n8n 2.47.7 (versiunea stabilă) și Slack Web API.
Integrarea n8n cu Slack: Construirea de Automatizări Puternice pentru Workflow-uri
Slack este hub-ul de comunicare pentru multe echipe, ceea ce îl face o platformă ideală pentru notificări și interacțiuni automatizate. Acest ghid acoperă pattern-uri complete pentru integrarea Slack cu n8n.
Configurarea de Bază a Slack
Configurarea Credențialelor OAuth
// Slack OAuth scopes needed for full functionality
const requiredScopes = {
bot: [
'channels:history',
'channels:read',
'channels:join',
'chat:write',
'chat:write.public',
'files:read',
'files:write',
'groups:history',
'groups:read',
'im:history',
'im:read',
'im:write',
'reactions:read',
'reactions:write',
'users:read',
'users:read.email'
],
user: [
'channels:read',
'groups:read',
'users:read'
]
};Notificare Simplă prin Mesaj
Pentru o notificare simplă folosești nodul Slack cu resursa Message și operația Send, alegi canalul și scrii textul ca expresie, de exemplu 🚨 Alert: {{ $json.alertType }}. Pentru orice are câmpuri, culori sau butoane construiești blocuri Block Kit într-un Code node (secțiunea următoare) și le trimiți cu aceeași operație, în locul câmpurilor vechi de attachment.
Formatarea Mesajelor Complexe
Constructor de Mesaje Block Kit
// Code node (Run Once for All Items): build a Block Kit alert message.
// Escape &, < and > in values that come from outside, so they can't inject Slack links or mentions.
const esc = (value) => String(value ?? '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
const buildAlertMessage = (alert) => {
const severityEmoji = {
critical: '🔴',
high: '🟠',
medium: '🟡',
low: '🟢'
};
const now = Math.floor(Date.now() / 1000);
return {
blocks: [
{
type: 'header',
text: {
type: 'plain_text',
text: `${severityEmoji[alert.severity] ?? '⚪'} ${alert.title}`,
emoji: true
}
},
{
type: 'section',
fields: [
{ type: 'mrkdwn', text: `*Service:*\n${esc(alert.service)}` },
{ type: 'mrkdwn', text: `*Environment:*\n${esc(alert.environment)}` },
{ type: 'mrkdwn', text: `*Severity:*\n${esc(String(alert.severity).toUpperCase())}` },
{
type: 'mrkdwn',
text: `*Time:*\n<!date^${now}^{date_short_pretty} at {time}|${new Date().toISOString()}>`
}
]
},
{
type: 'section',
text: { type: 'mrkdwn', text: `*Description:*\n${esc(alert.description)}` }
},
{
type: 'actions',
elements: [
{
type: 'button',
text: { type: 'plain_text', text: '✅ Acknowledge', emoji: true },
style: 'primary',
action_id: 'acknowledge_alert',
value: JSON.stringify({ alertId: alert.id, action: 'acknowledge' })
},
{
type: 'button',
text: { type: 'plain_text', text: '🔇 Silence (1h)', emoji: true },
action_id: 'silence_alert',
value: JSON.stringify({ alertId: alert.id, action: 'silence', duration: 3600 })
},
{
type: 'button',
text: { type: 'plain_text', text: '📊 View Details', emoji: true },
action_id: 'view_details',
url: `https://monitoring.example.com/alerts/${encodeURIComponent(alert.id)}`
}
]
},
{
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `Alert ID: ${esc(alert.id)} | <https://runbook.example.com/${encodeURIComponent(alert.runbookId)}|View Runbook>`
}
]
}
]
};
};
return [{ json: buildAlertMessage($input.first().json) }];Notificare de Deployment
// Code node (Run Once for All Items): deployment notification
const deployment = $input.first().json;
const esc = (value) => String(value ?? '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
const statusConfig = {
started: { emoji: '🚀', color: '#439FE0' },
success: { emoji: '✅', color: 'good' },
failed: { emoji: '❌', color: 'danger' },
rolled_back: { emoji: '⏪', color: 'warning' }
};
const config = statusConfig[deployment.status] || { emoji: '❓', color: '#808080' };
const message = {
attachments: [
{
color: config.color,
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: `${config.emoji} *Deployment ${esc(String(deployment.status).toUpperCase())}*`
}
},
{
type: 'section',
fields: [
{ type: 'mrkdwn', text: `*Application:*\n${esc(deployment.application)}` },
{ type: 'mrkdwn', text: `*Environment:*\n${esc(deployment.environment)}` },
{ type: 'mrkdwn', text: `*Version:*\n${esc(deployment.version)}` },
{ type: 'mrkdwn', text: `*Deployed by:*\n<@${esc(deployment.deployedBy)}>` }
]
}
]
}
]
};
if (deployment.commits && deployment.commits.length > 0) {
const commitList = deployment.commits
.slice(0, 5)
.map(c => `• \`${esc(c.sha.substring(0, 7))}\` ${esc(c.message.split('\n')[0])}`)
.join('\n');
message.attachments[0].blocks.push({
type: 'section',
text: { type: 'mrkdwn', text: `*Changes:*\n${commitList}` }
});
}
if (deployment.status === 'failed' && deployment.error) {
message.attachments[0].blocks.push({
type: 'section',
text: { type: 'mrkdwn', text: `*Error:*\n\`\`\`${esc(deployment.error)}\`\`\`` }
});
}
return [{ json: message }];Mesaje Interactive
Verifică semnăturile cererilor Slack
Fiecare interacțiune, slash command și eveniment care ajunge la nodul Webhook trebuie verificat înainte să ruleze orice altceva. Activezi Raw Body pe nodul Webhook, pentru că Slack semnează body-ul brut al cererii, și pui primul Code node-ul de mai jos. El parsează și body-ul, ca nodurile de după să citească $json.body la fel, fie că cererea e form-encoded, fie JSON.
// Code node (Run Once for All Items), first node after the Webhook ("Raw Body" enabled).
// Self-hosted: NODE_FUNCTION_ALLOW_BUILTIN=crypto. On n8n 2.x, $env in the Code node
// needs N8N_BLOCK_ENV_ACCESS_IN_NODE=false.
const crypto = require('crypto');
const item = $input.first();
const headers = item.json.headers;
const timestamp = Number(headers['x-slack-request-timestamp']);
const signature = headers['x-slack-signature'];
const signingSecret = $env.SLACK_SIGNING_SECRET;
const binaryKey = Object.keys(item.binary ?? {})[0];
if (!signature || !signingSecret || !binaryKey) {
throw new Error('Missing Slack signature data');
}
// Reject requests more than five minutes old (replay protection)
if (!Number.isFinite(timestamp) || Math.abs(Math.floor(Date.now() / 1000) - timestamp) > 300) {
throw new Error('Slack request timestamp outside the five-minute window');
}
const rawBody = (await this.helpers.getBinaryDataBuffer(0, binaryKey)).toString('utf8');
const expected = 'v0=' + crypto
.createHmac('sha256', signingSecret)
.update(`v0:${timestamp}:${rawBody}`)
.digest('hex');
const received = Buffer.from(String(signature));
const computed = Buffer.from(expected);
if (received.length !== computed.length || !crypto.timingSafeEqual(received, computed)) {
throw new Error('Invalid Slack signature');
}
const isJson = String(headers['content-type'] ?? '').includes('application/json');
const body = isJson ? JSON.parse(rawBody) : Object.fromEntries(new URLSearchParams(rawBody));
return [{ json: { ...item.json, body } }];Gestionarea Click-urilor pe Butoane
// Code node (Run Once for All Items), after the signature check.
// Slack sends interactions as application/x-www-form-urlencoded with a "payload" field
// holding JSON, and expects HTTP 200 within 3 seconds: respond early with Respond to Webhook.
const payload = JSON.parse($input.first().json.body.payload);
const parseValue = (value) => {
if (!value) return {};
try {
return JSON.parse(value);
} catch {
return { raw: value }; // plain string values, for example an incident ID
}
};
const action = payload.actions?.[0];
const actionValue = parseValue(action?.value);
const interaction = {
type: payload.type,
user: { id: payload.user?.id, name: payload.user?.name },
channel: payload.channel?.id,
responseUrl: payload.response_url,
triggerId: payload.trigger_id,
message: payload.message, // the original message, used to update it afterwards
action: action ? { id: action.action_id, value: actionValue, blockId: action.block_id } : null
};
switch (interaction.action?.id) {
case 'acknowledge_alert':
return [{ json: { ...interaction, workflow: 'acknowledge_alert', alertId: actionValue.alertId } }];
case 'silence_alert':
return [{
json: {
...interaction,
workflow: 'silence_alert',
alertId: actionValue.alertId,
duration: actionValue.duration
}
}];
case 'approve_request':
return [{ json: { ...interaction, workflow: 'approve_request', requestId: actionValue.requestId } }];
default:
return [{ json: { ...interaction, workflow: 'unknown_action' } }];
}Actualizarea Mesajului după Interacțiune
// Code node (Run Once for All Items): replace the buttons once someone has acted.
// Send the result with an HTTP Request node (POST to url, JSON body).
// A response_url accepts up to 5 responses within 30 minutes.
const interaction = $input.first().json;
const blocks = interaction.message?.blocks ?? [];
const now = Math.floor(Date.now() / 1000);
const updatedBlocks = blocks.map(block => block.type === 'actions'
? {
type: 'section',
text: {
type: 'mrkdwn',
text: `✅ *Acknowledged by <@${interaction.user.id}>* at <!date^${now}^{date_short_pretty} {time}|now>`
}
}
: block);
return [{
json: {
url: interaction.responseUrl,
method: 'POST',
body: {
replace_original: true,
blocks: updatedBlocks
}
}
}];Slash Commands
Handler pentru Slash Commands
// Code node (Run Once for All Items), after the signature check:
// route a slash command (form fields text, user_id, user_name, channel_id,
// response_url and trigger_id arrive in $json.body)
const command = $input.first().json.body;
const parts = String(command.text ?? '').trim().split(/\s+/).filter(Boolean);
const subCommand = parts[0] || 'help';
const args = parts.slice(1);
const commandRouter = {
'help': () => ({
workflow: 'show_help',
responseType: 'ephemeral'
}),
'status': () => ({
workflow: 'get_status',
service: args[0] || 'all',
responseType: 'in_channel'
}),
'deploy': () => ({
workflow: 'trigger_deploy',
application: args[0],
environment: args[1] || 'staging',
version: args[2] || 'latest',
responseType: 'in_channel'
}),
'incident': () => ({
workflow: 'create_incident',
title: args.join(' '),
responseType: 'in_channel'
}),
'oncall': () => ({
workflow: 'get_oncall',
team: args[0],
responseType: 'ephemeral'
})
};
const handler = commandRouter[subCommand] || commandRouter['help'];
const result = handler();
return [{
json: {
...result,
userId: command.user_id,
userName: command.user_name,
channelId: command.channel_id,
responseUrl: command.response_url,
triggerId: command.trigger_id
}
}];Dialog Modal pentru Input Complex
// Code node (Run Once for All Items): body for a views.open call (HTTP Request node,
// POST https://slack.com/api/views.open with the Slack credential).
// trigger_id expires three seconds after Slack sends it and works only once,
// so open the modal before any slow step.
const triggerId = $input.first().json.triggerId;
const modal = {
trigger_id: triggerId,
view: {
type: 'modal',
callback_id: 'create_incident_modal',
title: {
type: 'plain_text',
text: 'Create Incident'
},
submit: {
type: 'plain_text',
text: 'Create'
},
close: {
type: 'plain_text',
text: 'Cancel'
},
blocks: [
{
type: 'input',
block_id: 'title_block',
label: {
type: 'plain_text',
text: 'Incident Title'
},
element: {
type: 'plain_text_input',
action_id: 'title_input',
placeholder: {
type: 'plain_text',
text: 'Brief description of the incident'
}
}
},
{
type: 'input',
block_id: 'severity_block',
label: {
type: 'plain_text',
text: 'Severity'
},
element: {
type: 'static_select',
action_id: 'severity_select',
options: [
{ text: { type: 'plain_text', text: 'SEV1 - Critical' }, value: 'sev1' },
{ text: { type: 'plain_text', text: 'SEV2 - High' }, value: 'sev2' },
{ text: { type: 'plain_text', text: 'SEV3 - Medium' }, value: 'sev3' },
{ text: { type: 'plain_text', text: 'SEV4 - Low' }, value: 'sev4' }
]
}
},
{
type: 'input',
block_id: 'services_block',
label: {
type: 'plain_text',
text: 'Affected Services'
},
element: {
type: 'multi_static_select',
action_id: 'services_select',
options: [
{ text: { type: 'plain_text', text: 'API Gateway' }, value: 'api-gateway' },
{ text: { type: 'plain_text', text: 'Web App' }, value: 'web-app' },
{ text: { type: 'plain_text', text: 'Database' }, value: 'database' },
{ text: { type: 'plain_text', text: 'Auth Service' }, value: 'auth' }
]
}
},
{
type: 'input',
block_id: 'description_block',
label: {
type: 'plain_text',
text: 'Description'
},
element: {
type: 'plain_text_input',
action_id: 'description_input',
multiline: true,
placeholder: {
type: 'plain_text',
text: 'Detailed description of the incident, impact, and any known information'
}
}
}
]
}
};
return [{ json: modal }];Gestionarea Trimiterii Modalului
// Code node (Run Once for All Items), after the signature check: modal submission.
// The response object goes back through Respond to Webhook within 3 seconds.
const payload = JSON.parse($input.first().json.body.payload);
if (payload.type !== 'view_submission') {
return [];
}
const values = payload.view.state.values;
const incident = {
title: values.title_block.title_input.value,
severity: values.severity_block.severity_select.selected_option.value,
services: values.services_block.services_select.selected_options.map(o => o.value),
description: values.description_block.description_input.value,
reporter: {
id: payload.user.id,
name: payload.user.name
},
createdAt: new Date().toISOString()
};
return [{
json: {
incident,
response: {
response_action: 'clear'
}
}
}];Abonamente la Evenimente
Gestionarea Evenimentelor Slack
// Code node (Run Once for All Items), after the signature check: route Events API requests.
// For url_verification, send { challenge } back with a Respond to Webhook node.
const event = $input.first().json.body;
if (event.type === 'url_verification') {
return [{ json: { challenge: event.challenge } }];
}
if (event.type === 'event_callback') {
const slackEvent = event.event;
const eventHandlers = {
'message': () => handleMessage(slackEvent),
'app_mention': () => handleMention(slackEvent),
'reaction_added': () => handleReaction(slackEvent),
'channel_created': () => handleChannelCreated(slackEvent),
'team_join': () => handleTeamJoin(slackEvent)
};
const handler = eventHandlers[slackEvent.type];
if (handler) {
return [{ json: handler() }];
}
}
return [];
function handleMessage(event) {
// Ignore bot messages, including the app's own
if (event.bot_id || event.subtype === 'bot_message') {
return { skip: true };
}
return {
type: 'message',
text: event.text,
user: event.user,
channel: event.channel,
ts: event.ts,
threadTs: event.thread_ts
};
}
function handleMention(event) {
return {
type: 'mention',
text: event.text,
user: event.user,
channel: event.channel,
ts: event.ts
};
}
function handleReaction(event) {
return {
type: 'reaction',
reaction: event.reaction,
user: event.user,
item: event.item
};
}
function handleChannelCreated(event) {
return {
type: 'channel_created',
channel: event.channel
};
}
function handleTeamJoin(event) {
return {
type: 'team_join',
user: event.user
};
}Workflow-uri ChatOps
Workflow-ul pentru Comanda de Deploy
// Complete deploy workflow triggered by slash command
// Step 1: Validate permissions
const request = $json;
const allowedDeployers = ['U123456', 'U789012']; // User IDs
const protectedEnvironments = ['production'];
// Check permissions
if (protectedEnvironments.includes(request.environment)) {
if (!allowedDeployers.includes(request.userId)) {
return [{
json: {
error: true,
message: {
response_type: 'ephemeral',
text: '❌ You do not have permission to deploy to production. Contact #platform-team for access.'
}
}
}];
}
}
// Acknowledge command immediately
const acknowledgement = {
response_type: 'in_channel',
text: `🚀 Deployment initiated by <@${request.userId}>`,
attachments: [{
color: '#439FE0',
fields: [
{ title: 'Application', value: request.application, short: true },
{ title: 'Environment', value: request.environment, short: true },
{ title: 'Version', value: request.version, short: true },
{ title: 'Status', value: 'Starting...', short: true }
]
}]
};
return [{
json: {
acknowledgement,
deployRequest: request,
responseUrl: request.responseUrl
}
}];Notificarea On-Call
// Code node (Run Once for All Items): page the on-call engineer.
// onCall comes from an earlier node (your on-call schedule or paging tool).
const incident = $input.first().json;
const onCallUser = incident.onCall;
const message = {
channel: onCallUser.slackId, // DM to on-call
text: '🚨 You are being paged for an incident',
blocks: [
{
type: 'header',
text: {
type: 'plain_text',
text: '🚨 INCIDENT ALERT - Action Required',
emoji: true
}
},
{
type: 'section',
text: {
type: 'mrkdwn',
text: `*${incident.title}*\n\n${incident.description}`
}
},
{
type: 'section',
fields: [
{
type: 'mrkdwn',
text: `*Severity:*\n${String(incident.severity).toUpperCase()}`
},
{
type: 'mrkdwn',
text: `*Services:*\n${(incident.services || []).join(', ')}`
}
]
},
{
type: 'actions',
elements: [
{
type: 'button',
text: {
type: 'plain_text',
text: '✅ Acknowledge',
emoji: true
},
style: 'primary',
action_id: 'ack_incident',
value: String(incident.id)
},
{
type: 'button',
text: {
type: 'plain_text',
text: '📞 Join War Room',
emoji: true
},
action_id: 'join_war_room',
url: incident.warRoomUrl
},
{
type: 'button',
text: {
type: 'plain_text',
text: '📋 View Runbook',
emoji: true
},
action_id: 'view_runbook',
url: incident.runbookUrl
}
]
}
]
};
// Same message in the incident channel: channel goes after the spread,
// otherwise message.channel (the DM) would overwrite it
const channelMessage = {
...message,
channel: '#incidents'
};
return [
{ json: { type: 'dm', message } },
{ json: { type: 'channel', message: channelMessage } }
];Bune Practici
Rate Limiting și Gestionarea Erorilor
Limitele Slack sunt pe metodă și pe workspace: metodele Tier 1 permit 1+ cerere pe minut, Tier 2 20+, Tier 3 50+ și Tier 4 100+, iar chat.postMessage are o limită proprie și permite în general un mesaj pe secundă pe canal, cu toleranță pentru scurte rafale. Când depășești o limită, Slack răspunde HTTP 429 cu header-ul Retry-After, care spune câte secunde să aștepți. În n8n nu ai nevoie de Redis pentru asta: trimiți mesajele în masă prin Loop Over Items, cu un nod Wait de circa o secundă pe mesaj către același canal, și activezi Retry On Fail pe nodul Slack, cu Wait Between Tries de câteva secunde, ca un 429 ocazional să fie reîncercat în loc să pice rularea.
Thread-uri de Mesaje
// Code node (Run Once for All Items): reply in a thread
const input = $input.first().json;
const threadedMessage = {
channel: input.channel,
thread_ts: input.parentTs,
reply_broadcast: false, // set true to also post the reply to the channel
text: input.text,
blocks: input.blocks
};
return [{ json: threadedMessage }];Concluzie
O integrare eficientă a Slack cu n8n permite capabilități puternice de ChatOps:
- Notificări Complexe - Folosește Block Kit pentru mesaje informative și acționabile
- Workflow-uri Interactive - Butoane, modal-uri și slash commands
- Gestionarea Evenimentelor - Reacționează la evenimentele din canale și acțiunile utilizatorilor
- ChatOps - Deploy, verificare status și gestionare incidente direct din Slack
Pattern-urile astea aduc alertele, aprobările și pașii de incident în Slack, unde echipa lucrează deja, cu fiecare cerere primită verificată și fiecare răspuns trimis în limitele de timp ale Slack.
Surse oficiale
- Verifying requests from Slack
- Handling user interaction in your Slack apps
- Rate limits
- Slack node
- n8n v2.0 breaking changes
Pe același subiect: n8n securitate workflow: protejarea integrarilor, Automatizare AI: Zapier vs Make vs n8n - Pe care sa o alegi?, Workflow-uri n8n cu AI: pattern-uri de integrare. Mai multe articole în categoria n8n Automation.