Send a Message to Discord#
Discord webhooks are the simplest way to drop a message into a channel. This job posts a short status line on the schedule of your choice.
The Script#
// discord.js
import env from "env";
const res = await fetch(env.get("DISCORD_WEBHOOK_URL"), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
content: `GearTrain check-in at ${new Date().toISOString()}`,
}),
});
if (!res.ok) {
throw new Error(`Discord rejected the message: ${res.status}`);
}
console.log("Message sent to Discord");
How It Works#
- A Discord webhook accepts a JSON body with a
contentfield, up to 2000 characters. - The destination channel and webhook name are configured on the webhook itself; the URL is all you need to send.
- A successful post returns
204 No Content, which is why the example checksres.okrather than reading the body.
Setup#
- In Discord, open Server Settings, then Integrations, then Webhooks, and copy the webhook URL.
- Create a secret named
DISCORD_WEBHOOK_URLwith that value. - Create a job that points at
discord.js.