怎么增加可在运行时输入读取的配置文件?

HAMI_8307855824 · 1 天前

回答

Hamibot AI
1
· 1 天前

要在Hamibot中增加可在运行时输入读取的配置文件,你可以通过以下方法实现:

方法一:使用对话框获取输入并保存配置

// 文档地址 https://docs.hamibot.com/
// 创建配置读写函数
function getConfig() {
    var configPath = files.path("./config.json");
    if (files.exists(configPath)) {
        var configStr = files.read(configPath);
        return JSON.parse(configStr);
    }
    return {};
}

function saveConfig(config) {
    files.writeJSON("./config.json", config);
}

// 运行时获取配置
function setupConfig() {
    var config = getConfig();
    
    // 如果没有配置或需要重新配置
    if (!config.username || !config.server) {
        dialogs.build({
            title: "系统配置",
            content: "请输入系统配置信息",
            inputHint: "用户名",
            inputPrefill: config.username || "",
            positive: "保存",
            negative: "取消"
        }).on("input", function(input) {
            config.username = input;
        }).on("positive", function() {
            dialogs.input("服务器地址", config.server || "").then(function(server) {
                config.server = server;
                saveConfig(config);
                toast("配置已保存");
            });
        }).show();
    }
    return config;
}

// 使用示例
var config = setupConfig();
toast("当前配置: 用户名=" + config.username + ", 服务器=" + config.server);

方法二:使用控制台输入

// 文档地址 https://docs.hamibot.com/
// 读取配置文件
function readConfig() {
    var path = "./config.txt";
    if (files.exists(path)) {
        return JSON.parse(files.read(path));
    }
    return {};
}

// 保存配置文件
function writeConfig(config) {
    files.write("./config.txt", JSON.stringify(config));
}

// 主程序
var config = readConfig();

// 如果是首次运行或需要重新配置
if (!config.apiKey) {
    console.show();
    console.log("请输入API密钥:");
    config.apiKey = console.rawInput("API密钥: ");
    writeConfig(config);
    console.hide();
}

toast("配置加载完成,API密钥: " + config.apiKey.substring(0, 5) + "...");

方法三:结合使用脚本引擎参数传递配置

// 文档地址 https://docs.hamibot.com/
// 主脚本 main.js
var config = {
    timeout: 3000,
    retry: 3
};

// 通过参数传递配置
var e = engines.execScriptFile("./worker.js", {
    arguments: {
        config: config,
        mode: "advanced"
    }
});

// worker.js 中可以这样获取
// var config = engines.myEngine().config;
// toast("使用配置: " + JSON.stringify(config));

最佳实践建议

  1. 配置文件位置:将配置文件保存在脚本目录下(./config.json),这样可以随脚本一起备份

  2. 安全考虑:敏感信息(如密码)不要明文存储,可以考虑简单加密

  3. 默认配置:提供合理的默认配置,避免每次运行都需要输入

  4. 配置验证:在保存配置前进行基本验证,确保输入格式正确

  5. 用户友好:对于复杂配置,可以分步骤引导用户完成配置

如果需要更复杂的配置管理,建议结合使用dialogs模块创建多步骤配置向导,或者使用console模块提供命令行式的配置界面。

ℹ️ 本回答由 AI 生成,内容仅供参考