【问题标题】:Discord.js Command to change a Variable in the Config.jsonDiscord.js 命令更改 Config.json 中的变量
【发布时间】:2021-08-09 23:19:08
【问题描述】:

最近,我向我的机器人添加了从我的config.json 获取文件中嵌入的颜色的功能。我所要做的就是将其从 "embedcolor": "00A950" 更改为 "embedcolor": "00000" 但我想知道如何发出命令来更改此变量?我想它会像:-embedcolorset [HexCode] 那样工作,机器人会改变配置文件中的颜色。

感谢您的帮助:)

【问题讨论】:

    标签: javascript node.js discord discord.js bots


    【解决方案1】:

    您可以使用fs.readFile 读取文件的内容,使用fs.writeFile 将数据写入文件(如果文件已存在则替换该文件)。

    您也可以使用Util.resolveColor 来验证用户提供的颜色。

    确保您创建的config.json 文件至少包含一个空对象 ({}),否则您将收到 SyntaxError

    查看下面的工作代码:

    const { Client, Util } = require('discord.js');
    const fs = require('fs');
    const path = require('path');
    
    const TOKEN = 'BOT TOKEN';
    const client = new Client();
    const prefix = '!';
    
    // helper function to read the JSON file
    function jsonRead(filePath) {
      return new Promise((resolve, reject) => {
        fs.readFile(filePath, 'utf-8', (err, content) => {
          if (err) {
            reject(err);
          } else {
            try {
              resolve(JSON.parse(content));
            } catch (err) {
              reject(err);
            }
          }
        });
      });
    }
    
    // helper function to write the JSON file
    function jsonWrite(filePath, data) {
      return new Promise((resolve, reject) => {
        fs.writeFile(filePath, JSON.stringify(data), (err) => {
          if (err) {
            reject(err);
          }
          resolve(true);
        });
      });
    }
    
    client.on('message', async (msg) => {
      const args = msg.content.slice(prefix.length).split(/ +/);
      const command = args.shift().toLowerCase();
    
      if (command === 'embedcolorset') {
        // path to the config.json file
        // mine is in the same folder as this file
        const filePath = path.resolve(__dirname, './config.json');
    
        // check if the provided colour is a valid one
        if (isNaN(Util.resolveColor(args[0]))) {
          return msg.channel.send('You need to provide a valid colour');
        }
    
        try {
          // read the file content, it's a simple object now
          const config = await jsonRead(filePath);
          // update the embedcolor property
          config.embedcolor = args[0];
    
          // save the file with the updated settings
          jsonWrite(filePath, config);
    
          msg.channel.send(`Embed colour is set to ${config.embedcolor}`);
        } catch (err) {
          console.log(err);
        }
      }
    });
    
    client.once('ready', () => {
      console.log('Bot is connected...');
    });
    
    client.login(TOKEN);
    

    【讨论】:

    • 太棒了!它有效,非常感谢。无论如何要添加一些代码以使其重新启动机器人?我注意到它在重新启动之前不会更新机器人,这不是一个大问题,但会很酷!
    • 不客气。您可能不需要重新启动您的机器人,只需更新配置,但是,我不确定您如何存储或加载它。
    • 我有重新加载它的答案:function requireUncached(module) { delete require.cache[require.resolve(module)]; return require(module)}. 然后每次你想访问它时,做 var whatever = requireUncached('./filename');抱歉,格式很糟糕,我在移动网站上
    • “var whatever”是什么?它会和这个进入同一个文件吗?
    • @ZsoltMeszaros 你知道为什么突然现在它不起作用了吗?使用相同的代码,我什至无法让机器人做出响应。
    猜你喜欢
    • 1970-01-01
    • 2021-09-21
    • 2023-01-29
    • 2020-06-29
    • 2018-01-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2020-08-12
    相关资源
    最近更新 更多