所以我有这个代码:
const Discord = require("discord.js");
const bot = new Discord.Client();
const rf = require("select-random-file");
const token = "{DATA REVOKED}";
const prefix = "bot:"
const dir = './RandomImage'
function ranIm(){
rf(dir, (err, file) => {
console.log(`The random file is: ${file}.`)
return file;
})
}
bot.on('ready', () =>{
bot.user.setStatus("Online");
bot.user.setActivity('with '+bot.guilds.cache.size+" servers!");
console.log("{BOT INITIALISED} PREFIX IS "+prefix)
})
bot.on("message", msg=>{
let contentDown =msg.content.toLowerCase();
let args = contentDown.substring(prefix.length).split(" ");
if(contentDown.substring(0,prefix.length)===prefix){
switch(args[0]){
case 'random':
console.log(ranIm());
msg.channel.send("Here is your image: <3", { files:["./RandomImage/"+ranIm()]}).then(() => {
msg.react("✅")}, err => {console.log("Error [random]"); msg.react("❌") });
break;
}
}
})
bot.login(token);
答案 0 :(得分:0)
您的函数ranIm
本身不返回任何内容。 return file
在rf
函数的第二个参数内。因此,返回文件现在是rf(dir, ...)
函数的结果。
因此,您需要为ranIm
函数提供一个回调参数,如下所示:
function ranIm(callback){
rf(dir, (err, file) => {
console.log(`The random file is: ${file}.`)
callback(file)
})
}
ranIm(function(randomFile) {
// Do stuff with random file
})
另一个选择是使用Promises
function ranIm(callback){
return new Promise((reject, resolve) {
rf(dir, (err, file) => {
if (err) reject(err);
resolve(file);
})
})
}
ranIm().then(file => {
// Do stuff with random file
})