The low effort way of sending messages to a discord channel from Node.js
We recently opened up a Discord Server for Hashnode users (yay! finally ๐). Yesterday I had some time to set up a channel for incoming dev stories from Hashnode's Devblog network. Initially this sounded simple, but I faced some hiccups!
Firstly, I went with the Bot route and created a new bot that'll periodically push content from Hashnode to a specific channel. This is a pretty small feature and I was expecting to do this under 30-40 LOC. Also, I didn't want to introduce a whole new module for this task. So, I didn't use discord.js (which is what everyone uses to interact with Discord from Node.js).
I went ahead and tried calling their HTTP endpoint as a bot, but kept getting 4001 errors. I am pretty sure I supplied the correct credentials. After some googling someone suggested that the bot must interact with the gateway (I had no idea what a gateway is) first in order to be able to send messages to a channel. Then I started reading up about gateway, but quickly lost interest since I had more important things to do yesterday.
I started thinking how come there is no easy way to send a message Discord channel programmatically. Luckily, I stumbled upon Webhooks and wrapped the feature within 10 minutes (and 10 LOC). โ๏ธ
So, if you are looking for a quick and low effort way to send messages to a Discord channel from Node.js, follow the steps below:
Step 1
Register your webhook by clicking on the settings icon present on the right side of channel name. It'll open up a modal. Navigate to "Webhooks" tab from left hand menu and click "Create Webhook".
Give your webhook a name and copy the URL.
Step 2
In your Node.js app, paste the following code when you are ready to trigger messages:
const url = `<YOUR WEBHOOK URL>`;
const fetch = require('node-fetch');
function sendMessage(message) {
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({"username": "Hashnode Bot", "content": `New blog post ๐ [${message.title}](${message.url})`})
});
}
Done!
Note: You can use markdown in the content field as shown above!
If you like tinkering with terminal and want to interact with Discord via curl, follow this guide instead: https://birdie0.github.io/discord-webhooks-guide/tools/curl.html
// Keep Rocking