javascript - 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)
希望我提供了足够的信息。
解决方案
read.readPath()
基本上返回void
or 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
也会更容易理解。
推荐阅读
- c++ - 打印出用户从未输入的数字的数组副本
- spring - Spring 的 @RefreshScope 是坏了还是我用错了?
- python-2.7 - 尝试在数组中设置值
- javascript - Firebase 云函数“函数返回未定义、预期的承诺或值”
- r - 如何使用 R 中的非标准多项式函数调整非线性曲线拟合的系数
- java - Ganib (Java) - 无法发送验证邮件
- visual-studio-code - 在 Windows 中使用非默认终端
- c++ - 正在使用空指针调用静态成员 UB
- javascript - 使用 lodash 或 ramda 转换对象数组
- networking - 页面在有机会呈现之前重新加载