javascript - 为什么我的程序在管理这个 JSON 文件时会崩溃?
问题描述
每当有人发送!setmainchannel
时,我的程序就会崩溃。我正在使用带有包 discord.js 的 Node.js。这是我唯一的问题。我不明白也不明白出了什么问题,如果有人能帮助我,我将不胜感激。
bot.js
:
let Discord = require("discord.js");
let client = new Discord.Client();
let fs = require('fs');
let help = require("./helpembed.json");
var jsonRead = function(filePath){
fs.readFile(filePath, 'utf-8', (err, returnJson) => {
if(err){
console.log(err);
}
else{
let ret = JSON.parse(returnJson);
return ret;
}
})
}
var jsonWrite = function(filePath, objIn){
fs.writeFile(filePath, JSON.stringify(objIn), err => {
if(err){
console.log(err);
}
})
}
client.on("message", msg => {
let time = new Date();
let cstTimeStamp = `${time.getMonth() + 1}/${time.getDate()}/${time.getFullYear()} ${time.getHours() + 1}:${time.getMinutes()}:${time.getSeconds()}`
if(msg.content == "!setmainchannel"){
let mainChannel = msg.mentions.channels.first();
if(!mainChannel){
console.log(`${cstTimeStamp} @${msg.author.tag} requested to set a main channel but didn't provide a channel\n`);
msg.channel.send("There's no channel to set the main to");
}
else{
let currentSettings = jsonRead("./main-channel.json");
currentSettings.channel = mainChannel;
jsonWrite("./main-channel.json", currentSettings);
console.log(`${cstTimeStamp} @${msg.author.tag} set the main channel as ${currentSettings.channel}\n`);
msg.channel.send(`Set the main channel as ${currentSettings.channel}`);
}
}
})
client.once('ready', () => {
console.log('Bot is online\n');
});
client.login('Token hidden for safety reasons');
main-channel.json
:
{
"channel":null
}
解决方案
首先,您的机器人什么都不做,因为它只会做出反应if (msg.content == "!setmainchannel")
。如果您提供参数,例如通道 ( !setmainchannel #ch-name
),它将不会运行,因为消息的内容不完全是前缀和命令。
你需要先解决这个问题。通过删除前缀并切掉参数,您可以获得命令本身并检查是否使用了这个确切的命令。(同样,你不应该检查整个message.content
)
其次,您不必等待内部的回调readFile
运行。这意味着,当您尝试更新时currentSettings.channel
,您的jsonRead()
函数刚刚开始读取文件并且currentSettings
是undefined
. 您将无法更新其channel
属性。
我已经更新了您的jsonWrite
和jsonRead
函数以返回承诺并使其更易于使用。检查下面的工作代码:
const Discord = require("discord.js");
const fs = require('fs');
const path = require('path');
const client = new Discord.Client();
const prefix = '!';
client.on('message', async (msg) => {
// create an args variable that slices off the prefix and splits it into an array
const args = msg.content.slice(prefix.length).split(/ +/);
// create a command variable by taking the first element in the array
// and removing it from args
const command = args.shift().toLowerCase();
const cstTimeStamp = new Date().toLocaleString();
if (command === 'setmainchannel') {
const mainChannel = msg.mentions.channels.first();
const filePath = path.resolve(__dirname, './main-channel.json');
if (!mainChannel) {
console.log(`${cstTimeStamp} ${msg.author.tag} requested to set a main channel but didn't provide a channel\n`);
return msg.channel.send("There's no channel to set the main to");
}
try {
const currentSettings = await jsonRead(filePath);
currentSettings.channel = mainChannel;
jsonWrite(filePath, currentSettings);
console.log(`${cstTimeStamp} ${msg.author.tag} set the main channel as ${currentSettings.channel}\n`);
msg.channel.send(`Set the main channel as ${currentSettings.channel}`);
} catch (err) {
console.log(err);
}
}
});
client.once('ready', () => {
console.log('Bot is online\n');
});
client.login('Token hidden for safety reasons');
function jsonRead(filePath) {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf-8', (err, content) => {
if (err) {
reject(err);
} else {
try {
const parsedContent = JSON.parse(content);
resolve(parsedContent);
} catch (err) {
reject(err);
}
}
});
});
}
function jsonWrite(filePath, data) {
return new Promise((resolve, reject) => {
fs.writeFile(filePath, JSON.stringify(data), (err) => {
if (err) {
reject(err);
}
resolve(true);
});
});
}
推荐阅读
- jquery - 在 NodeJS-Express 应用程序的 DOM 操作中使用 jQuery
- ios - 在领域中存储值
- php - DevTools 中的错误不再显示 XHR 响应
- python - 我无法下载 cv2,无论出于何种原因它都不起作用
- image - tensorflow仿射变换填充值
- html - 如何将跨度与h2放在同一行?
- python - 使用基本用户名和密码通过 Python 从 CloudFront 下载文件
- c++ - 显示带有二维数组的文件
- java - Java 9+ 相当于清单定义的启动画面
- python-3.x - Zipfile 无法解压缩 NFS 驱动器中存在的文件