javascript - 如何再次读取配置文件并更新 Discord 机器人的前缀?
问题描述
我在 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.readFile
,你很好
推荐阅读
- javascript - 在反应 useEffect 生命周期中,我得到了无限的结果
- python - 无法正确启动 Scrapy shell
- spring - 我如何解决错误邮递员401未经授权
- r - Dplyr 中的 Vlookup() 等效项
- python - 运行 django-admin 后出现“bash: django-admin: command not found”
- ruby-on-rails - 如何在 Rails 中创建 has_many 关系记录?
- google-developers-console - 我可以从谷歌开发者控制台获取我的项目源代码吗
- php - php用大写单词替换描述中的特定单词并循环遍历它
- php - 即使浏览器在codeigniter中关闭,如何保持用户登录
- apache-nifi - NiFi 中是否有任何处理器可以帮助我为每条记录添加唯一标识符?