首页 > 解决方案 > 如何再次读取配置文件并更新 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": "!"
}

标签: javascriptnode.jsjsondiscord.jsfs

解决方案


如果您想通过 访问数据require,它不会在以后更新,因为该函数在项目开始时运行一次,即使您重新需要它。这篇文章可以给你更多的背景知识。基本上:总是使用fs.readFile,你很好


推荐阅读