【问题标题】:Discord bot Command That changes Value of a different commandDiscord bot 命令改变了不同命令的值
【发布时间】:2022-11-21 10:19:36
【问题描述】:

我正在寻找一种通过在不同命令中键入新值来更改文本字符串或一个命令中的值的方法。例如,我有 Discord js v12,我正在使用模块命令,每个命令都在它自己的 .js 文件中。

module.exports = {
    name: 'calc',
    cooldown: 1000,
    run: async(client, message, args) => {
        if (!message.member.hasPermission("ADMINISTRATOR")) return await message.delete();
        await message.delete();

        var multiply = args[0] * (100 - percalc) / 100;
        var calculation = multiply.toFixed(2);
        
        if(!args[0]) return await message.channel.send('Specify a Value');

        await message.channel.send(changableValue);
        await message.channel.send(calculation < 5 ? 5 : calculation);
    }

我在配置文件中有常量

const percalc = 50;
const changableValue = 'Text example';

现在命令_calc {number}基于percalc常量和changableValue部分附带的文本进行百分比计算。 我想做一个命令,比如_calcset {Value},它将保存提供的值并将它发送到代替changableValue const。

【问题讨论】:

    标签: javascript discord discord.js


    【解决方案1】:

    首先,请注意关键字const 存在的唯一原因是因为它代表constant 并且常量变量永远无法更改。因此,请确保将变量更改为普通的var

    现在,如果您只想在每个会话中更改变量,并且您可以将它恢复到您关闭机器人时定义的状态,您可以使用从 js 文件导出的函数更新变量。但是要获得动态变量,您还需要使用导出的 getter 函数。例子:

    配置.js

    var changeableValue = "foo";
    
    function getValue() {
        return changeableValue;
    }
    
    function updateValue(newValue) {
        changeableValue = newValue;
    }
    
    module.exports = {
        getValue,
        updateValue
    }
    

    命令.js

    const { getValue, updateValue } = require("config.js");
    
    console.log(getValue()); // logs "foo"
    updateValue("bar");
    console.log(getValue()); // logs "bar"
    

    不幸的是,正如我提到的,每次关闭机器人时,changeableValue var 都会重置回“foo”。如果这对你没问题,那么上面的工作正常。

    如果你想通过会话持久化 changeableValue 变量,那么它会变得有点复杂。您最可能的两个选择是使用 fs module 将值写入 JSON 文件(这样它将保存到您的磁盘),或者将值保存在其他数据库中,例如 MongoDB。我建议使用其他数据库提供程序,因为在写入自己的磁盘时可能会遇到更多问题,例如,如果您同时发出两个写入请求(比如两个用户同时使用该命令),当请求尝试同时写入时,您可能会损坏文件。但是,设置外部数据库不在您的问题范围内,因此这里是设置写入 JSON 文件的方式:

    配置.json

    {
        "changeableValue": "foo"
    }
    

    命令.js

    const fs = require("fs");
    var { changeableValue } = require("config.json");
    console.log(changeableValue) // logs "foo"
    
    var updatedValueJSON = JSON.stringify({ changeableValue: "bar" }); // necessary because the JSON object must be converted to a string
    
    fs.writeFile("config.json", updatedValueJSON, "utf8", () => {
        // this is the callback function called when the file write completes
        let { changeableValue } = require("config.json");
    
        console.log(changeableValue); // logs "bar", and now if you restart the bot and import changeableValue, it will still be bar
    });
    

    【讨论】:

      猜你喜欢
      • 2018-03-04
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 2021-08-28
      • 2020-10-25
      • 2018-10-21
      相关资源
      最近更新 更多