Send a Message to Slack#
Post to a Slack channel using an incoming webhook. Create the webhook in Slack, store its URL as a secret, and this job can deliver alerts, digests, and status updates.
The Script#
// slack.js
import env from "env";
const message = {
text: `GearTrain ran at ${new Date().toISOString()}`,
};
const res = await fetch(env.get("SLACK_WEBHOOK_URL"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(message),
});
if (!res.ok) {
throw new Error(`Slack rejected the message: ${res.status}`);
}
console.log("Message sent to Slack");
How It Works#
- A Slack incoming webhook takes a JSON body with a
textfield. Slack uses its ownmrkdwnsyntax, which is inspired by Markdown but differs. For example,*bold*,_italic_, and<https://example.com|link text>. - The webhook URL is a secret. Anyone who has it can post to the channel, so treat it like a password.
- Slack replies
200with the bodyokon success.
Setup#
- Create a Slack app, then enable Incoming Webhooks.
- Click Add New Webhook to Workspace, choose a channel, and copy the webhook URL.
- Create a secret named
SLACK_WEBHOOK_URLwith that value. - Create a job that points at
slack.jsand run it once.
To send to several channels, store one secret per channel and pass the name into a helper function.