【发布时间】:2020-12-19 05:04:05
【问题描述】:
我在 Discord 机器人中更改编码前缀时遇到了一些问题。我已经完成了所有基本功能:
- 前缀保存在配置文件中
- 机器人可以写入文件并保存以备后用
但是,在我重新启动机器人之前,我似乎无法让机器人在更改后使用新前缀。配置文件显示前缀已更改,但机器人没有响应。
所以,我的问题是,如何刷新内存以重新加载配置,或者如何让机器人再次读取我的配置并使用新前缀?
谢谢!
prefix.js:
const fs = require('fs'); // node.js file system module
config = require('../config.json');
const Discord = require("discord.js");
module.exports = {
name: 'prefix', // command keyword
description: 'Changes the bot prefix', // info about command
group: 'settings', // command group (not displayed in !help [command name])
aliases: ['botprefix', 'newprefix'], // using these keywords also triggers command
usage: '[new prefix]', // how command is supposed to be used
cooldown: '1', // time command cannot be reused after it has been called
args: true, // are arguments required
execute(message, args) {
fs.exists("../config.json", function (error) {
if (error) {
console.log(error);
}
})
? fs
.readFile("../config.json", function (error) {
if (error) {
console.log(error);
}
})
.toString()
: config.prefix;
const newPrefix = args.shift().toString();
newConfig = {
token: config.token,
prefix: newPrefix,
};
fs.writeFile("config.json", JSON.stringify(newConfig, null, 2), function (
error
) {
if (error) {
console.log(error);
}
});
}
config.json:
{
"token": "token",
"prefix": "!"
}
【问题讨论】:
-
第一次加载配置的情况如何?使用 require 还是使用 fs?
-
@zer0,哎呀。当我提出问题时,我一定忘记复制和粘贴文件的那一部分。我已经对其进行了编辑以包含该信息。我想我正在使用两种方式来加载配置。不过不确定。
-
我看不到您在哪里加载配置。是的,你在
prefix命令中使用fs.readFile来获取config.json的内容,但是结果没有用到。
标签: javascript node.js json discord.js fs