This repository was archived by the owner on Mar 31, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmemory.js
More file actions
72 lines (60 loc) · 1.93 KB
/
memory.js
File metadata and controls
72 lines (60 loc) · 1.93 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
const fs = require("fs");
const path = "./messageMemory.json";
// Initialize as a const object so the reference never changes
const memory = {};
let saveTimeout = null;
// Load existing memory
function loadMemory() {
if (fs.existsSync(path)) {
const rawData = fs.readFileSync(path, "utf8");
try {
const parsedData = JSON.parse(rawData);
// Clear current keys (optional, but good practice)
for (const key in memory) delete memory[key];
// Merge loaded data into the existing 'memory' constant
Object.assign(memory, parsedData);
} catch (e) {
console.error("Error parsing memory file:", e);
}
} else {
fs.writeFileSync(path, JSON.stringify({}, null, 2));
}
}
// Save memory back to file with debouncing
function saveMemory() {
if (saveTimeout) clearTimeout(saveTimeout);
saveTimeout = setTimeout(async () => {
saveTimeout = null; // clear synchronously before async I/O
try {
await fs.promises.writeFile(path, JSON.stringify(memory, null, 2));
} catch (err) {
console.error("Error saving memory file:", err);
}
}, 5000); // 5 second debounce
}
// Add a logged message
// Updated to include timestamp
function logMessage(channelId, memberName, message, timestamp = Date.now()) {
logMessagesBatch(channelId, [{ memberName, message, timestamp }]);
}
function logMessagesBatch(channelId, messages) {
if (!messages || messages.length === 0) return;
if (!memory[channelId]) {
memory[channelId] = [];
}
for (const msg of messages) {
memory[channelId].push({
memberName: msg.memberName,
message: msg.message,
timestamp: msg.timestamp || Date.now()
});
}
saveMemory();
}
module.exports = {
loadMemory,
saveMemory,
logMessage,
logMessagesBatch,
memory
};