【问题标题】:How can I read config file again and update prefix for Discord bot?如何再次读取配置文件并更新 Discord 机器人的前缀?
【发布时间】: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


【解决方案1】:

如果您想通过require 访问数据,它不会在以后更新,因为该函数在项目开始时运行一次,即使您重新需要它。 This 文章可以为您提供更多背景知识。基本上:始终使用 fs.readFile 就可以了

【讨论】:

  • 您可以删除缓存,如果您重新需要它,数据将是新的。我个人会坚持使用 fs.readFile。
猜你喜欢
  • 1970-01-01
  • 2021-01-24
  • 2021-04-25
  • 2020-04-07
  • 2020-06-03
  • 2021-11-17
  • 2021-09-03
  • 2021-08-29
  • 2021-07-29
相关资源
最近更新 更多