首页 > 解决方案 > DiscordAPIError:无法发送空消息

问题描述

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

尝试使用不和谐机器人创建日历并获得有利的“无法发送空消息”。该机器人能够读取命令并在特定文件上使用 fs.readFileSync 会返回有利的结果。

但是,我正在尝试使用 fs.readdir 首先获取文件列表,然后使用 for 循环遍历它们。console.log 显示了良好的结果,但机器人显示 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)

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

标签: javascriptnode.jsdiscord.js

解决方案


read.readPath()基本上返回voidor undefined

为什么?因为您readFile()在回调函数本身中返回。它不会超出fs.readdir功能。所以里面的回调函数readdir返回值 not 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)
        })
    }

但同样,Promises与 , 一起使用async/await也会更容易理解。


推荐阅读