[英]how to get discord.js to pick a random image from file
我在另一个泡菜中,我在过去一周意识到由于链接已过期,我的图像没有加载,所以我想了解如何在代码中使用文件目录。
这是我尝试过的:
});
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
var fs = require('fs');
var files = fs.readdirSync('C:\Users\nevbw\Desktop\games\FBIBot\images\hugs')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)]
}
});
和
});
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
const path = 'C:\Users\nevbw\Desktop\games\FBIBot\images\hugs';
const fs = require('fs');
fs.readdirSync(path).forEach(file => {
ranfile = Math.floor(Math.random() * file.length);
message.channel.sendFile(ranfile);
})
}
});
通过搜索和搜索发现,但找到了一个答案,将其修改为此,我希望人们在将来的参考中使用它! const num = (Math.floor(Math.random()* 5)+1).toString(); message.channel.send({files: [`./slap/slap${num}.gif`]})
使用 fs.readdirSync('./images/') 而不是 fs.readFileSync('./images/') 工作更容易,但是你必须在 VSC 内部创建文件夹并将图像放在文件夹中,你可以还将图像拖放到解决方案中并使用:
var files = fs.readdirSync(`./images/`).filter(file => file.endsWith('.png'))
这样当它寻找图像时,它不会选择其他任何东西。 希望它对某些人有所帮助。
乐于帮助。
您以错误的方式使用 FS。 这就是它应该是什么样子 :D 这里还有一些关于它的文档 ( https://nodejs.org/dist/latest-v13.x/docs/api/fs.html )。
- 代码 -
也只是提示! 我看到您正在使用完整目录,这很不合理(例如,如果您更改了用户名、驱动器 ID 等),因此在 fs 中,只要图像位于同一文件夹中,您就可以执行 ./(ImageName),或者如果它是在同一文件夹中,但在另一个说 /FBIBot/Images 下,您可以执行 ./Images/(ImageName)。 ^^
——
错误是什么:(不幸的是我无法测试它,但我 99% 肯定)。
您正在使用fs.readdirSync(path).forEach(file => {
当您打算使用fs.readfilesync(path).forEach(file => {
.
-- 第一个代码 --
});
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
var fs = require('fs');
var files = fs.readfileSync('C:\Users\nevbw\Desktop\games\FBIBot\images\hugs')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)]
}
});
-- 第二个代码 --
});
client.on('message', message => {
if (message.content.startsWith('L!hug')) {
var fs = require('fs');
var files = fs.readFileSync('C:\Users\nevbw\Desktop\games\FBIBot\images\hugs')
/* now files is an Array of the name of the files in the folder and you can pick a random name inside of that array */
let chosenFile = files[Math.floor(Math.random() * files.length)]
}
});
^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.