Sending Discord Messages in Node.js with Fetch

This post is an update to Simple Discord Messages in Python, but this time in JavaScript! We’re going to use some simple code for sending a Discord message without the need of any Discord API library.

Here’s the basic code:

const BOT_TOKEN = 'xxxxx';
const CHANNEL_ID = '#####';
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));

async function sendMessage(content) {
    const response = await fetch(
        `https://discord.com/api/v9/channels/${CHANNEL_ID}/messages`, {
            method: 'post',
            body: JSON.stringify({content}),
            headers: {
                'Authorization': `Bot ${BOT_TOKEN}`,
                'Content-Type': 'application/json',
            }
        }
    );
    const data = await response.json();
    return data;
}

To run the function, simply add this line:

sendMessage('hello world!');

To send a message along with an attached image from an external URL, we’ll have to modify the code and use FormData, like this:

const BOT_TOKEN = 'xxxxx';
const CHANNEL_ID = '#####';
const FormData = require('form-data');
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));

async function sendMessageAndImage(content, imageUrl) {
    const imageRes = await fetch(imageUrl).then(res => res.body);
    let formdata = new FormData();
    formdata.append("files[0]", imageRes, 'chart.png');
    formdata.append("payload_json", JSON.stringify({
        content
    }));
    const response = await fetch(
        `https://discord.com/api/v9/channels/${CHANNEL_ID}/messages`, {
            method: 'post',
            body: formdata,
            headers: {
                'Authorization': `Bot ${BOT_TOKEN}`,
            }
        }
    );
    const data = await response.json();
    return data;
}

And here is how to invoke the function:

sendMessageAndImage('foobar', 'https://avatars.githubusercontent.com/u/9919');