从文件夹中的文件创建数组并随机发送 [英] Creating an array from files in a folder and sending them randomly
本文介绍了从文件夹中的文件创建数组并随机发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为 Discord.js 机器人创建一个命令,当触发该命令时,将使用从文件夹创建的数组,选择随机图像,然后发送.
I am trying to create a command for a Discord.js bot that when triggered, will use an array created from a folder, select a random image, then send it.
我无法手动设置数组,因为文件夹中的图像数量总是会发生变化.
I can't set the array manually because the amount of images in the folder is always going to be changing.
这就是我所拥有的:
if(command.toLowerCase() == "command"){
const fs = require('fs');
const imageFolderLocation = "./images/";
var imageArray = [];
fs.readdir(imageFolderLocation, (err, files) => {
imageArray = files;
});
let randomImage = Math.floor(Math.random() * imageArray.length) + 1;
for (var i = 0; i < imageArray.length; i++) {
message.channel.sendFile(randomImage);
}
return;
}
我尝试使用 --trace-warnings
启动机器人,但无济于事.没有警告打印到控制台.
I tried starting the bot with --trace-warnings
but it was to no avail. No warnings printed to console.
推荐答案
我看到的一些问题:
- fs.readdir 是异步的,你不能在回调之外使用 files/imageArray
- 您发送的是随机整数而不是图像
- 您发送 randomImage imageArray.length 次
- 你忽略了错误
更正的代码:
if (command.toLowerCase() == "command") {
const fs = require('fs');
const imageFolderLocation = "./images/";
fs.readdir(imageFolderLocation, (err, imageArray) => {
// TODO if (err) { /* print to console or something */ }
let randomIndex = Math.floor(Math.random() * imageArray.length) + 1;
let randomImage = imageArray[randomIndex];
message.channel.sendFile(randomImage);
});
return;
}
这篇关于从文件夹中的文件创建数组并随机发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文