'Discord.js | How do I make my bot send a random image?

I have tried a bunch of things that I've seen and none of them seem to be working for me. I am using the thing where when you do a command it activates a file in the commands folder, and most of the other scripts dont use that.

1



Solution 1:[1]

Without seeing any code, it is quite difficult to point you in the right direction. It would help more to define the issue you are having (actual errors and/or functionality) along with seeing the code you are using. The solution also depends on where the images are coming from.

Assuming your images are in a local folder, here is a basic example:

if (message.content === '!random') {
    // get a random index between 0 and length
    const idx = (len) => Math.floor(Math.random() * (len));

    // get all the files in the directory
    const files = fs.readdirSync('/images/');

    // get file from directory
    const myImage = files[idx(files.length)];
    
    // send image to channel
    message.channel.send({ files: [`/images/${myImage}`] });
}

Assuming images are from https://picsum.photos/, here is an basic example:

if (message.content === '!random') {
    const seed = Math.floor(Math.random() * 1000);
    const h = Math.floor(Math.random() * 400) + 100;
    const w = Math.floor(Math.random() * 400) + 100;
    
    // create embed with random image
    const embed = new MessageEmbed().setImage(`https://picsum.photos/seed/${seed}/${h}/${w}`);
    
    // send embed
    message.channel.send({ embeds: [embed] });

    // delete command
    message.delete();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1