DiscordAPIError:无法发送空消息

时间:2019-12-14 09:59:47

标签: javascript node.js discord.js

第一次问一个问题。经历了类似的问题,但似乎与我的询问不符。

尝试使用Discord bot创建日历并获得良好的“无法发送空消息”。该机器人可以读取命令,并在特定文件上使用fs.readFileSync返回良好的结果。

但是,我尝试使用fs.readdir首先获取文件列表,然后使用for循环遍历它们。 console.log显示良好的结果,但是bot显示DiscordAPIError:无法发送空消息。

readFS.js file

var fs = require("fs");

function readPath(){

    fs.readdir('./calendar/', function(err, list){
        if(err) throw err;

        for(let i=0; i<list.length; i++){
            return readFile('./calendar/'+list[i]);
            //return list[i];
        }
    })
}

function readFile(file, err){
    if(err) return err;

    console.log(JSON.parse(fs.readFileSync(file)))
    return JSON.stringify(JSON.parse(fs.readFileSync(file)));

}

process.on('unhandledRejection', (reason, promise) => {
    console.log('Unhandled Rejection at:', reason.stack || reason)
})

module.exports = {
    readFile,
    readPath
}

如果可能的话,我想远离诺言,因为诺言对我来说很难完全理解。不和谐的机器人可以毫无问题地分辨出我的观点。

bot.js file
else if(arguments.length > 0 && arguments[0] == "view" && arguments[1] == 'list'){
        receivedMessage.channel.send("Retreiving Calendar!")
        receivedMessage.channel.send(read.readPath())
        //console.log(read.readPath())

    }

控制台中的实际错误:

Command received: calendar
Arguments: view,list
{ Title: 'Test Event',
  Description: 'Event for testing the output of JSON',
  StartDate: 'Today',
  StartTime: '3 hours from now',
  LockedTo: 'Guild Only' }
Unhandled Rejection at: DiscordAPIError: Cannot send an empty message
    at item.request.gen.end (C:\Users\afrederick\Documents\GitHub\xtreamexe\node_modules\discord.js\src\client\rest\RequestHandlers\Sequential.js:85:15)
    at then (C:\Users\afrederick\Documents\GitHub\xtreamexe\node_modules\snekfetch\src\index.js:215:21)
    at process._tickCallback (internal/process/next_tick.js:68:7)

希望我提供了足够的信息。

1 个答案:

答案 0 :(得分:0)

read.readPath()基本上返回voidundefined

为什么?因为您要在回调函数本身中返回readFile()。它并没有超出fs.readdir函数的范围。因此readdir内部的回调函数返回的值不是fs.readdir。希望这是有道理的。

首先,使用promise,回调是混乱且过时的。

但是,如果您想要一个简单的回调解决方案,则必须向readPath添加另一个回调,然后从那里调用它:-)

function readPath(cb){

    fs.readdir('./calendar/', function(err, list){
        if(err) throw err;

        for(let i=0; i<list.length; i++){
            return cb(null, readFile('./calendar/'+list[i]));
            //return list[i];
        }
    })
}

bot.js文件

else if(arguments.length > 0 && arguments[0] == "view" && arguments[1] == 'list'){
        read.readPath(function(err, data){
            receivedMessage.channel.send("Retreiving Calendar!")
            receivedMessage.channel.send(data)
        })
    }

但同样,将Promisesasync/await结合使用,也会更容易理解。

相关问题