回答
要使用配置文件和本地文件,需结合 hamibot.env
配置管理模块和 files
文件操作模块,具体步骤如下:
1. 配置文件使用方法
创建配置文件(config.json)
{
"logPath": "/sdcard/hamibot_logs/",
"maxLogSize": 1048576,
"defaultMsg": "✅ Hamibot 机能正常"
}
上传配置文件
通过 API 上传时需指定 MIME 类型:
curl -X PUT \
-H "Authorization: hmp_xxxx" \
-F "data=@config.json;type=application/json" \
https://api.hamibot.com/v1/devscripts/脚本ID/files
在脚本中读取配置
// 文档地址 https://docs.hamibot.com/
const { logPath, defaultMsg } = hamibot.env;
// 使用配置值
toastLog(defaultMsg);
console.setGlobalLogConfig({
file: logPath + "app.log",
maxFileSize: hamibot.env.maxLogSize || 512 * 1024
});
2. 本地文件操作
基础文件操作
// 创建目录
const LOG_DIR = hamibot.env.logPath || "./logs/";
if (!files.exists(LOG_DIR)) {
files.ensureDir(LOG_DIR);
}
// 写入文件(自动创建)
files.write(LOG_DIR + "readme.txt", "这是一个测试文件");
// 读取文件
const content = files.read(LOG_DIR + "readme.txt");
console.log("文件内容:" + content);
日志文件进阶操作
// 按日期分割日志
const today = new Date().toISOString().slice(0, 10);
const LOG_FILE = LOG_DIR + "log_" + today + ".txt";
// 追加写入日志
function writeLog(msg) {
const time = new Date().toLocaleString();
files.append(LOG_FILE, `[${time}] ${msg}\n`);
}
writeLog("执行开始");
// ...执行操作...
writeLog("执行结束");
3. 注意事项
- 配置文件最大体积 3MB,需通过 API 单独或与脚本文件同时上传
- 本地文件路径建议使用
/sdcard/
开头的绝对路径 - 使用
files.exists()
检查文件是否存在,避免空指针异常 - 读写大文件时注意内存限制,建议分块操作(单个文件不宜超过 10MB)
完整示例:结合配置文件的路径设置,动态创建日志目录并写入日志内容,实现日志自动按日期归档功能。
ℹ️ 本回答由 AI 生成,内容仅供参考