Browse Month

November 2021

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');

Stop “npm install” in Heroku

I have a node.js project that I want to run on Heroku, but with my own modified node plugins in the node_modules folder. When deploying the project to Heroku, it keeps installing brand new node dependencies, which overwrites my modified ones.

According to this Stack Overflow answer, “npm install” always runs and cannot be blocked or skipped. However, there is one workaround, which is to create a .npmrc file in the project root with the following contents: dry-run

The dry-run setting tells npm that we do not want to make any changes to the node_modules folder, thus keeping our node plugins unaffected!