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 text field. Slack uses its own mrkdwn syntax, 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 200 with the body ok on success.

Setup#

  1. Create a Slack app, then enable Incoming Webhooks.
  2. Click Add New Webhook to Workspace, choose a channel, and copy the webhook URL.
  3. Create a secret named SLACK_WEBHOOK_URL with that value.
  4. Create a job that points at slack.js and run it once.

To send to several channels, store one secret per channel and pass the name into a helper function.