forked from hihumanzone/Gemini-Discord-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbotManager.js
More file actions
359 lines (313 loc) · 9.14 KB
/
botManager.js
File metadata and controls
359 lines (313 loc) · 9.14 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
import dotenv from 'dotenv';
dotenv.config();
import {
Client,
GatewayIntentBits,
Partials
} from 'discord.js';
import {
GoogleGenAI,
createUserContent,
createPartFromUri
} from '@google/genai';
import fs from 'fs/promises';
import path from 'path';
import {
fileURLToPath
} from 'url';
import config from './config.js';
// --- Core Client and API Initialization ---
// Using new Google GenAI library instead of deprecated @google/generative-ai
export const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.DirectMessages,
],
partials: [Partials.Channel],
});
// Initialize with new API format that requires apiKey object
export const genAI = new GoogleGenAI({ apiKey: process.env.GOOGLE_API_KEY });
export { createUserContent, createPartFromUri };
export const token = process.env.DISCORD_BOT_TOKEN;
// --- Concurrency and Request Management ---
export const activeRequests = new Set();
class Mutex {
constructor() {
this._locked = false;
this._queue = [];
}
acquire() {
return new Promise(resolve => {
if (!this._locked) {
this._locked = true;
resolve();
} else {
this._queue.push(resolve);
}
});
}
release() {
if (this._queue.length > 0) {
const nextResolve = this._queue.shift();
nextResolve();
} else {
this._locked = false;
}
}
async runExclusive(callback) {
await this.acquire();
try {
return await callback();
} finally {
this.release();
}
}
}
export const chatHistoryLock = new Mutex();
// --- State and Data Management ---
let chatHistories = {};
let activeUsersInChannels = {};
let customInstructions = {};
let serverSettings = {};
let userResponsePreference = {};
let userToolPreference = {};
let alwaysRespondChannels = {};
let channelWideChatHistory = {};
let blacklistedUsers = {};
export const state = {
get chatHistories() {
return chatHistories;
},
set chatHistories(v) {
chatHistories = v;
},
get activeUsersInChannels() {
return activeUsersInChannels;
},
set activeUsersInChannels(v) {
activeUsersInChannels = v;
},
get customInstructions() {
return customInstructions;
},
set customInstructions(v) {
customInstructions = v;
},
get serverSettings() {
return serverSettings;
},
set serverSettings(v) {
serverSettings = v;
},
get userResponsePreference() {
return userResponsePreference;
},
set userResponsePreference(v) {
userResponsePreference = v;
},
get userToolPreference() {
return userToolPreference;
},
set userToolPreference(v) {
userToolPreference = v;
},
get alwaysRespondChannels() {
return alwaysRespondChannels;
},
set alwaysRespondChannels(v) {
alwaysRespondChannels = v;
},
get channelWideChatHistory() {
return channelWideChatHistory;
},
set channelWideChatHistory(v) {
channelWideChatHistory = v;
},
get blacklistedUsers() {
return blacklistedUsers;
},
set blacklistedUsers(v) {
blacklistedUsers = v;
},
};
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const CONFIG_DIR = path.join(__dirname, 'config');
const CHAT_HISTORIES_DIR = path.join(CONFIG_DIR, 'chat_histories_4');
export const TEMP_DIR = path.join(__dirname, 'temp');
const FILE_PATHS = {
activeUsersInChannels: path.join(CONFIG_DIR, 'active_users_in_channels.json'),
customInstructions: path.join(CONFIG_DIR, 'custom_instructions.json'),
serverSettings: path.join(CONFIG_DIR, 'server_settings.json'),
userResponsePreference: path.join(CONFIG_DIR, 'user_response_preference.json'),
userToolPreference: path.join(CONFIG_DIR, 'user_tool_preference.json'),
alwaysRespondChannels: path.join(CONFIG_DIR, 'always_respond_channels.json'),
channelWideChatHistory: path.join(CONFIG_DIR, 'channel_wide_chathistory.json'),
blacklistedUsers: path.join(CONFIG_DIR, 'blacklisted_users.json')
};
// --- Data Persistence Functions ---
let isSaving = false;
let savePending = false;
export async function saveStateToFile() {
if (isSaving) {
savePending = true;
return;
}
isSaving = true;
try {
await fs.mkdir(CONFIG_DIR, {
recursive: true
});
await fs.mkdir(CHAT_HISTORIES_DIR, {
recursive: true
});
const chatHistoryPromises = Object.entries(chatHistories).map(([key, value]) => {
const filePath = path.join(CHAT_HISTORIES_DIR, `${key}.json`);
return fs.writeFile(filePath, JSON.stringify(value, null, 2), 'utf-8');
});
const filePromises = Object.entries(FILE_PATHS).map(([key, filePath]) => {
return fs.writeFile(filePath, JSON.stringify(state[key], null, 2), 'utf-8');
});
await Promise.all([...chatHistoryPromises, ...filePromises]);
} catch (error) {
console.error('Error saving state to files:', error);
} finally {
isSaving = false;
if (savePending) {
savePending = false;
saveStateToFile();
}
}
}
async function loadStateFromFile() {
try {
await fs.mkdir(CONFIG_DIR, {
recursive: true
});
await fs.mkdir(CHAT_HISTORIES_DIR, {
recursive: true
});
await fs.mkdir(TEMP_DIR, {
recursive: true
});
const files = await fs.readdir(CHAT_HISTORIES_DIR);
const chatHistoryPromises = files
.filter(file => file.endsWith('.json'))
.map(async file => {
const user = path.basename(file, '.json');
const filePath = path.join(CHAT_HISTORIES_DIR, file);
try {
const data = await fs.readFile(filePath, 'utf-8');
chatHistories[user] = JSON.parse(data);
} catch (readError) {
console.error(`Error reading chat history for ${user}:`, readError);
}
});
await Promise.all(chatHistoryPromises);
const filePromises = Object.entries(FILE_PATHS).map(async ([key, filePath]) => {
try {
const data = await fs.readFile(filePath, 'utf-8');
state[key] = JSON.parse(data);
} catch (readError) {
if (readError.code !== 'ENOENT') {
console.error(`Error reading ${key} from ${filePath}:`, readError);
}
}
});
await Promise.all(filePromises);
} catch (error) {
console.error('Error loading state from files:', error);
}
}
// --- Daily Cleanup and Initialization ---
function removeFileData(histories) {
try {
Object.values(histories).forEach(subIdEntries => {
subIdEntries.forEach(message => {
if (message.content) {
message.content = message.content.filter(contentItem => {
if (contentItem.fileData) {
delete contentItem.fileData;
}
return Object.keys(contentItem).length > 0;
});
}
});
});
console.log('fileData elements have been removed from chat histories.');
} catch (error) {
console.error('An error occurred while removing fileData elements:', error);
}
}
function scheduleDailyReset() {
try {
const now = new Date();
const nextReset = new Date();
nextReset.setHours(0, 0, 0, 0);
if (nextReset <= now) {
nextReset.setDate(now.getDate() + 1);
}
const timeUntilNextReset = nextReset - now;
setTimeout(async () => {
console.log('Running daily cleanup task...');
await chatHistoryLock.runExclusive(async () => {
removeFileData(chatHistories);
await saveStateToFile();
});
console.log('Daily cleanup task finished.');
scheduleDailyReset();
}, timeUntilNextReset);
} catch (error) {
console.error('An error occurred while scheduling the daily reset:', error);
}
}
export async function initialize() {
scheduleDailyReset();
await loadStateFromFile();
console.log('Bot state loaded and initialized.');
}
// --- State Helper Functions ---
export function getHistory(id) {
const historyObject = chatHistories[id] || {};
let combinedHistory = [];
// Combine all message histories for this ID
for (const messagesId in historyObject) {
if (historyObject.hasOwnProperty(messagesId)) {
combinedHistory = [...combinedHistory, ...historyObject[messagesId]];
}
}
// Transform to format expected by new Google GenAI API
return combinedHistory.map(entry => {
return {
role: entry.role === 'assistant' ? 'model' : entry.role,
parts: entry.content
};
});
}
export function updateChatHistory(id, newHistory, messagesId) {
if (!chatHistories[id]) {
chatHistories[id] = {};
}
if (!chatHistories[id][messagesId]) {
chatHistories[id][messagesId] = [];
}
chatHistories[id][messagesId] = [...chatHistories[id][messagesId], ...newHistory];
}
export function getUserResponsePreference(userId) {
return state.userResponsePreference[userId] || config.defaultResponseFormat;
}
export function getUserToolPreference(userId) {
return state.userToolPreference[userId] || config.defaultTool;
}
export function initializeBlacklistForGuild(guildId) {
try {
if (!state.blacklistedUsers[guildId]) {
state.blacklistedUsers[guildId] = [];
}
if (!state.serverSettings[guildId]) {
state.serverSettings[guildId] = config.defaultServerSettings;
}
} catch (error) {}
}