Repository navigation
Expand file tree
/
Copy pathmemory.js
More file actions
74 lines (61 loc) · 2.17 KB
/
Copy pathmemory.js
File metadata and controls
74 lines (61 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const fs = require('fs/promises');
const path = './data/history.json';
let writeQueue = Promise.resolve(); // serializes writes so concurrent saves don't clobber each other
async function ensureFileExists() {
try {
await fs.access(path);
const fileContent = (await fs.readFile(path, 'utf8')).trim();
if (!fileContent) {
await fs.writeFile(path, JSON.stringify({ history: {}, anger: {} }, null, 2));
}
} catch {
await fs.writeFile(path, JSON.stringify({ history: {}, anger: {} }, null, 2));
}
}
async function readStore() {
await ensureFileExists();
try {
const data = await fs.readFile(path, 'utf8');
const parsed = JSON.parse(data);
if (!parsed.history && !parsed.anger) {
return { history: parsed, anger: {} }; // migrate old flat format
}
parsed.history = parsed.history || {};
parsed.anger = parsed.anger || {};
return parsed;
} catch (error) {
console.error("Error reading history file:", error);
return { history: {}, anger: {} };
}
}
function writeStore(store) {
// queue writes so two concurrent saves can't interleave and corrupt the file
writeQueue = writeQueue.then(() =>
fs.writeFile(path, JSON.stringify(store, null, 2)).catch(error => {
console.error("Error writing to history file:", error);
})
);
return writeQueue;
}
async function getGuildHistory(guildId) {
const store = await readStore();
return store.history[guildId] || [];
}
async function saveGuildHistory(guildId, historyArray) {
const store = await readStore();
if (historyArray.length > 250) {
historyArray = historyArray.slice(-250);
}
store.history[guildId] = historyArray;
await writeStore(store);
}
async function getAngerLevel(guildId) {
const store = await readStore();
return store.anger[guildId] || { level: 0, lastAsk: 0 };
}
async function saveAngerLevel(guildId, angerState) {
const store = await readStore();
store.anger[guildId] = angerState;
await writeStore(store);
}
module.exports = { getGuildHistory, saveGuildHistory, getAngerLevel, saveAngerLevel };