简体   繁体   中英

How can I easily access the pictures of a folder?

I was commissioned to make a new Discord bot that does a list of things. One thing they wanted it to do was post a random picture from a folder they provided me with over 100 pictures. I really do not feel like storing all of those directories in an array, as that would take forever to type. Is there an easier way to access and randomly select an image to send without doing this?

let images = ["./pictures/image1.jpeg",, "./pictures/image2.jpeg", ....];
let index = Math.floor(Math.random() * 100);
message.channel.send({files: [picture[index]]});

The code above is what I am currently using and I have to add another 100 pictures to the array and I really do not want to type their directories all out.If you need to know the discord bot library it is discord.js. Any help is appreciated!

This function might work for you:

const fs = require('fs');

function randomFile(){
    const image_directory = './images/';
    let files = fs.readdirSync(image_directory).map(file => {
        return file;
    });

    return files[Math.floor(Math.random() * files.length)];
}

console.log(randomFile());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM