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 pathinitialise.js
More file actions
361 lines (306 loc) · 12 KB
/
initialise.js
File metadata and controls
361 lines (306 loc) · 12 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
360
361
require("dotenv").config();
const { loadMemory } = require("./memory.js");
// Initialize memory from disk before other modules are loaded
loadMemory();
const { setRandomStatus } = require("./functions/presence.js");
const { commands } = require("./functions/commands.js");
const {
handleInteraction,
handleUserRequest: handleWikiRequest,
responseMap,
botToAuthorMap,
pruneMap
} = require("./functions/interactions.js");
const { handleAIRequest } = require("./functions/ai_handler.js");
const {
Client,
GatewayIntentBits,
Partials,
ApplicationCommandType,
ContextMenuCommandBuilder,
ChannelType
} = require("discord.js");
const { WIKIS, CATEGORY_WIKI_MAP, STATUS_INTERVAL_MS, BOT_NAME, BOT_SETTINGS } = require("./config.js");
const { logMessage } = require("./memory.js");
const {
getHistory
} = require("./functions/conversation.js");
const DISCORD_TOKEN = process.env.DISCORD_TOKEN;
const {
IGNORED_CHANNELS,
TRIGGER_KEYWORDS,
RESPONSE_CHANCE,
MIN_FOLLOWUP_DELAY,
MAX_FOLLOWUP_DELAY
} = BOT_SETTINGS;
// --- FOLLOW-UP STATE MANAGER ---
const activeConversations = new Map();
// -------------------- UTILITIES --------------------
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
const PREFIX_WIKI_MAP = Object.keys(WIKIS).reduce((acc, key) => {
const prefix = WIKIS[key].prefix;
if (prefix) acc[prefix] = key;
return acc;
}, {});
const prefixPattern = Object.values(WIKIS).map(w => escapeRegExp(w.prefix)).join('|');
const syntaxRegex = new RegExp(
`\\{\\{(?:(${prefixPattern}):)?([^{}|]+)(?:\\|[^{}]*)?\\}\\}|` +
`\\[\\[(?:(${prefixPattern}):)?([^\\]|]+)(?:\\|[^[\\]]*)?\\]\\]`,
'i'
);
// -------------------- CLIENT SETUP --------------------
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.DirectMessageReactions,
GatewayIntentBits.MessageContent,
],
partials: [Partials.Channel, Partials.Message, Partials.Reaction],
});
client.once("ready", async () => {
console.log(`Logged in as ${client.user.tag}`);
const { loadPages } = require("./functions/parse_page.js");
await loadPages();
setRandomStatus(client);
setInterval(() => { setRandomStatus(client); }, STATUS_INTERVAL_MS);
try {
console.log("Registering slash commands...");
const allCommands = [...commands,
new ContextMenuCommandBuilder()
.setName(`Ask ${BOT_NAME}...`)
.setType(ApplicationCommandType.Message)
.setContexts([0, 1, 2])
.setIntegrationTypes([0, 1])
];
await client.application.commands.set(allCommands);
console.log("✅ Registered slash commands.");
} catch (err) {
console.error("Failed to register commands:", err);
}
});
// -------------------- FOLLOW-UP --------------------
async function scheduleFollowUp(message, wikiConfig) {
const channelId = message.channel.id;
if (activeConversations.has(channelId)) {
clearTimeout(activeConversations.get(channelId).timer);
}
if (Math.random() < 0.5) {
activeConversations.delete(channelId);
return;
}
const delay = Math.floor(Math.random() * (MAX_FOLLOWUP_DELAY - MIN_FOLLOWUP_DELAY + 1)) + MIN_FOLLOWUP_DELAY;
const timer = setTimeout(async () => {
try {
const channel = await client.channels.fetch(channelId).catch(() => null);
if (!channel) return;
const history = getHistory(channelId);
if (!history || history.length < 2) return;
const delayText = delay < 60000 ? `${Math.round(delay/1000)} seconds` : `${Math.round(delay/60000)} minutes`;
const systemNote = `[SYSTEM: It has been ${delayText} since you last spoke.
The user hasn't replied.
Construct a short, casual follow-up message based on the previous conversation context above.
Ask how they are, or bring up a related topic from the history.
You are also allowed to make a new topic with what you know about the conversation. You are not limited in talking about the current topic.
Do NOT greet them like it's the first time.
If the last conversation ended naturally (like "bye"), do not send anything and output [TERMINATE_MESSAGE].]`;
const mockMessage = {
channel: channel,
author: client.user,
client: client,
attachments: new Map(),
content: systemNote,
guild: channel.guild,
createdTimestamp: Date.now()
};
await handleAIRequest(systemNote, systemNote, mockMessage, wikiConfig, false, true);
} catch (err) {
console.error("Follow-up execution failed:", err);
} finally {
activeConversations.delete(channelId);
}
}, delay);
activeConversations.set(channelId, {
timer: timer,
lastInteraction: Date.now()
});
}
// -------------------- EVENTS --------------------
function getWikiAndPage(messageContent, channelParentId) {
const match = messageContent.match(syntaxRegex);
if (!match) return null;
const prefix = (match[1] || match[3])?.toLowerCase();
const rawPageName = (match[2] || match[4]).trim();
let wikiConfig = null;
if (prefix) {
wikiConfig = WIKIS[PREFIX_WIKI_MAP[prefix]];
} else {
const wikiKey = CATEGORY_WIKI_MAP[channelParentId] || "tagging";
wikiConfig = WIKIS[wikiKey];
}
return { wikiConfig, rawPageName };
}
client.on("messageCreate", async (message) => {
if (message.author.bot) return;
if (message.channel.name) {
const lowerName = message.channel.name.toLowerCase();
if (IGNORED_CHANNELS.some(blocked => lowerName.includes(blocked))) return;
}
logMessage(
message.channel.id,
message.author.username,
message.content,
message.createdTimestamp
);
const wikiKey = CATEGORY_WIKI_MAP[message.channel.parentId] || "tagging";
const defaultWikiConfig = WIKIS[wikiKey];
let wikiHandled = false;
const res = getWikiAndPage(message.content, message.channel.parentId);
if (res) {
const { wikiConfig, rawPageName } = res;
if (wikiConfig) {
const response = await handleWikiRequest(wikiConfig, rawPageName, message);
if (response && response.id) {
responseMap.set(message.id, response.id);
botToAuthorMap.set(response.id, message.author.id);
pruneMap(responseMap);
pruneMap(botToAuthorMap);
wikiHandled = true;
}
}
}
// AI Logic
let rawUserMsg = message.content.trim();
let promptMsg = rawUserMsg;
if (!rawUserMsg) return;
const isDM = !message.guild;
const mentioned = message.mentions.has(client.user);
let keywordTriggered = false;
if (!mentioned && !isDM) {
const lowerContent = rawUserMsg.toLowerCase();
const hasKeyword = TRIGGER_KEYWORDS.some(kw => lowerContent.includes(kw));
if (hasKeyword && Math.random() < RESPONSE_CHANCE) {
keywordTriggered = true;
}
}
let isReply = false;
if (message.reference) {
try {
const referenced = await message.channel.messages.fetch(message.reference.messageId);
isReply = referenced.author.id === client.user.id;
} catch {}
}
if (!(isDM || mentioned || isReply || keywordTriggered)) return;
if (wikiHandled) await new Promise(r => setTimeout(r, 1000));
if (message.reference) {
try {
const referencedMessage = await message.channel.messages.fetch(message.reference.messageId);
if (referencedMessage.content) {
const contextHeader = `[SYSTEM: I am replying to ${referencedMessage.author.username}'s message: "${referencedMessage.content}"]`;
promptMsg = `${contextHeader}\n\n${rawUserMsg}`;
}
} catch (err) {
console.error("Failed to fetch reply context:", err);
}
} else {
try {
const pastMessages = await message.channel.messages.fetch({ limit: 15, before: message.id });
const lastHumanMessages = pastMessages
.filter(m => !m.author.bot && m.content.trim().length > 0)
.first(5)
.reverse();
if (lastHumanMessages.length > 0) {
const contextLog = lastHumanMessages
.map(m => `[User: ${m.author.username}]: ${m.content}`)
.join("\n");
const contextBlock = `[SYSTEM: Here is the recent conversation context...:\n${contextLog}\n]`;
promptMsg = `${contextBlock}\n\n${rawUserMsg}`;
}
} catch (err) {
console.error("Failed to fetch channel context:", err);
}
}
await handleAIRequest(promptMsg, rawUserMsg, message, defaultWikiConfig);
if (isDM || mentioned || isReply) {
scheduleFollowUp(message, defaultWikiConfig);
}
});
client.on("messageUpdate", async (oldMessage, newMessage) => {
if (newMessage.partial) {
try {
await newMessage.fetch();
} catch (err) {
console.warn("Failed to fetch updated message:", err.message);
return;
}
}
if (oldMessage.partial) {
try {
await oldMessage.fetch();
} catch (err) {
console.warn("Failed to fetch old message content for update comparison:", err.message);
}
}
if (newMessage.author?.bot) return;
if (oldMessage.content === newMessage.content) return;
if (!responseMap.has(newMessage.id)) return;
const res = getWikiAndPage(newMessage.content, newMessage.channel.parentId);
if (!res) return;
const { wikiConfig, rawPageName } = res;
const botMessageId = responseMap.get(newMessage.id);
try {
const botMessage = await newMessage.channel.messages.fetch(botMessageId);
if (botMessage) {
const response = await handleWikiRequest(wikiConfig, rawPageName, newMessage, botMessage);
if (response && response.id) {
botToAuthorMap.set(response.id, newMessage.author.id);
pruneMap(botToAuthorMap);
}
}
} catch (err) {
console.warn("Failed to fetch bot message for update:", err.message);
}
});
client.on("messageReactionAdd", async (reaction, user) => {
if (user.bot) return;
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.error('Something went wrong when fetching the reaction:', error);
return;
}
}
const emoji = reaction.emoji.name;
const valid = new Set(["🗑️", "wastebasket"]);
if (valid.has(emoji)) {
const message = reaction.message;
if (message.author.id !== client.user.id) return;
let originalAuthorId = botToAuthorMap.get(message.id);
if (!originalAuthorId && message.reference) {
try {
const referencedMsg = await message.channel.messages.fetch(message.reference.messageId);
originalAuthorId = referencedMsg.author.id;
botToAuthorMap.set(message.id, originalAuthorId);
pruneMap(botToAuthorMap);
} catch (err) {
console.warn(`Failed to fetch referenced message ${message.reference.messageId} for bot message ${message.id}:`, err);
}
}
if (user.id === originalAuthorId) {
try {
await message.delete();
} catch (err) {
console.warn("Failed to delete message on reaction:", err.message);
}
}
}
});
client.on("interactionCreate", (interaction) => {
handleInteraction(interaction).catch(err => console.error("Interaction error:", err));
});
client.login(DISCORD_TOKEN);