-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.js
More file actions
610 lines (520 loc) · 21.4 KB
/
start.js
File metadata and controls
610 lines (520 loc) · 21.4 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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
require('dotenv').config();
const { Client } = require('discord.js-selfbot-v13');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
// ANSI Color codes for console logs
const colors = {
reset: "\x1b[0m",
red: "\x1b[31m",
green: "\x1b[32m",
yellow: "\x1b[33m",
blue: "\x1b[34m",
magenta: "\x1b[35m",
cyan: "\x1b[36m"
};
// Custom logger with colors
const logger = {
info: (message) => console.log(`${colors.blue}[INFO]${colors.reset} ${message}`),
success: (message) => console.log(`${colors.green}[SUCCESS]${colors.reset} ${message}`),
error: (message) => console.error(`${colors.red}[ERROR]${colors.reset} ${message}`),
warn: (message) => console.log(`${colors.yellow}[WARNING]${colors.reset} ${message}`),
separator: () => console.log(`${colors.cyan}${'='.repeat(50)}${colors.reset}`)
};
const client = new Client();
let baseUrl = process.env.OLLAMA_API_URL || 'http://localhost:11434';
const OLLAMA_API_URL = baseUrl.endsWith('/api/chat') ? baseUrl : `${baseUrl}/api/chat`;
const MODEL = process.env.OLLAMA_MODEL || '';
const MY_TOKEN = process.env.DISCORD_TOKEN;
const SHOW_THINKING = (process.env.SHOW_THINKING || 'false').toLowerCase() === 'true';
const LOG_CONVERSATIONS = (process.env.LOG_CONVERSATIONS || 'true').toLowerCase() === 'true';
const LOGS_FILE_PATH = process.env.LOGS_FILE_PATH || path.join(__dirname, 'conversations_log.json');
const DEBUG_MODE = (process.env.DEBUG_MODE || 'true').toLowerCase() === 'true';
const MEMORY_FOLDER = process.env.MEMORY_FOLDER || path.join(__dirname, 'bot_memory');
// Discord message character limit (free accounts)
const MESSAGE_CHAR_LIMIT = 2000;
const lastActivityTime = new Map();
// Inactivity duration before reset (configurable in minutes via env, 0 = disabled)
const INACTIVITY_TIMEOUT_MINUTES = parseInt(process.env.INACTIVITY_TIMEOUT_MINUTES || '5', 10);
const INACTIVITY_TIMEOUT = INACTIVITY_TIMEOUT_MINUTES > 0 ? INACTIVITY_TIMEOUT_MINUTES * 60 * 1000 : 0; // Convert minutes to milliseconds, 0 = disabled
// Structure to store conversation history by channel
const conversationHistory = new Map();
// Structure to store channel message history (for context)
const channelMessageHistory = new Map();
// Limit of history messages to keep per channel
const HISTORY_LIMIT = parseInt(process.env.HISTORY_LIMIT || '10', 10);
// Use history conversation feature
const USE_HISTORY_CONVERSATION = (process.env.USE_HISTORY_CONVERSATION || 'true').toLowerCase() === 'true';
// Number of recent messages to keep in memory per channel
const NB_MESSAGES_HISTORY = parseInt(process.env.NB_MESSAGES_HISTORY || '10', 10);
// Initial bot context
const BOT_CONTEXT = process.env.BOT_CONTEXT || "Do what do you want, but be nice and respectful.";
logger.separator();
logger.info('Starting Discord self-bot...');
logger.info(`Ollama API URL: ${OLLAMA_API_URL}`);
logger.info(`Model: ${MODEL || 'Not specified (will use Ollama default)'}`);
logger.info(`History limit: ${HISTORY_LIMIT} messages per channel`);
logger.info(`Use history conversation: ${USE_HISTORY_CONVERSATION}`);
if (USE_HISTORY_CONVERSATION) {
logger.info(`Channel message history: ${NB_MESSAGES_HISTORY} messages per channel`);
}
logger.info(`Inactivity timeout: ${INACTIVITY_TIMEOUT_MINUTES === 0 ? 'disabled (infinite memory)' : `${INACTIVITY_TIMEOUT_MINUTES} minutes`}`);
logger.info(`Show thinking : ${SHOW_THINKING}`);
logger.info(`Log conversations: ${LOG_CONVERSATIONS}`);
if (LOG_CONVERSATIONS) {
logger.info(`Log file path: ${LOGS_FILE_PATH}`);
}
if (DEBUG_MODE) {
logger.info(`Saving bot memory to ${MEMORY_FOLDER}`);
if (!fs.existsSync(MEMORY_FOLDER)) {
try {
fs.mkdirSync(MEMORY_FOLDER, { recursive: true });
logger.info(`Created memory folder at ${MEMORY_FOLDER}`);
} catch (error) {
logger.error(`Failed to create memory folder: ${error.message}`);
}
}
}
logger.separator();
client.on('ready', () => {
logger.success(`Connected as ${client.user.tag}`);
logger.separator();
});
// Function to check if the bot can send messages in a channel
function canSendMessages(channel) {
try {
// For text channels in guilds
if (channel.guild) {
const permissions = channel.permissionsFor(client.user.id);
return permissions && permissions.has('SEND_MESSAGES');
}
// For DMs, we assume we can send messages
return true;
} catch (error) {
logger.error(`Error checking permissions: ${error.message}`);
return false;
}
}
// Function to format <think> tags as quotes
function formatThinkTags(text) {
// Check if text contains <think> tags
if (text.includes('<think>') && text.includes('</think>')) {
if (SHOW_THINKING) {
logger.info('Found <think> tags in response, formatting as quotes');
// Replace each <think> block with a quote format
return text.replace(/<think>([\s\S]*?)<\/think>/g, (match, content) => {
// Convert the content to quote format by adding > to each line
const quoteContent = content
.trim()
.split('\n')
.map(line => `> ${line}`)
.join('\n');
return quoteContent;
});
} else {
logger.info('Found <think> tags in response, removing them');
// Remove each <think> block completely
return text.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
}
}
return text;
}
// Function to truncate message if it exceeds Discord's character limit
function truncateMessage(message) {
if (message.length <= MESSAGE_CHAR_LIMIT) {
return message;
}
logger.warn(`Message exceeds ${MESSAGE_CHAR_LIMIT} characters, truncating...`);
return message.substring(0, MESSAGE_CHAR_LIMIT - 3) + '...';
}
// Function to keep showing "typing..." indication during long operations
async function showTypingUntilDone(channel, operation) {
// Start typing indication
let hasTypingPermission = true;
const typingInterval = setInterval(() => {
if (hasTypingPermission) {
channel.sendTyping().catch(err => {
if (err.code === 50001) { // Missing Access error code
logger.warn(`No permission to show typing in channel #${channel.name || 'DM'}`);
hasTypingPermission = false; // Stop trying to send typing indicators
clearInterval(typingInterval);
} else {
logger.error(`Failed to send typing indicator: ${err.message}`);
clearInterval(typingInterval);
}
});
}
}, 5000); // Discord typing indicator lasts ~10 seconds, refresh every 5s
logger.info('Started typing indicator');
try {
// Wait for the operation to complete
const result = await operation();
// Stop typing indication
clearInterval(typingInterval);
logger.info('Stopped typing indicator');
return result;
} catch (error) {
// Stop typing indication on error too
clearInterval(typingInterval);
logger.info('Stopped typing indicator due to error');
throw error;
}
}
/*******************************/
// Inactivity timeout handling
// TEMPORARY SOLUTION: Using basic timeout for better stability. Will be enhanced in future versions.
/*******************************/
function checkInactiveChannels() {
const currentTime = Date.now();
lastActivityTime.forEach((lastTime, channelId) => {
// If more than the configured timeout has passed since the last activity
if (currentTime - lastTime > INACTIVITY_TIMEOUT) {
// If there is a history for this channel
if (conversationHistory.has(channelId)) {
const channelInfo = client.channels.cache.get(channelId);
const channelName = channelInfo ? (channelInfo.name || 'DM') : 'Unknown channel';
logger.info(`Resetting conversation history for inactive channel #${channelName} (${channelId})`);
conversationHistory.set(channelId, []); // Reset the bot conversation history
channelMessageHistory.set(channelId, []); // Reset the channel message history
lastActivityTime.delete(channelId); // Delete the time entry for this channel
// delete memory file
const serverName = channelInfo.guild ? channelInfo.guild.name : 'DirectMessages';
const safeSeverName = serverName.replace(/[\\/:*?"<>|]/g, '_').trim();
const safeChannelName = channelName.replace(/[\\/:*?"<>|]/g, '_').trim();
const channelFolder = path.join(MEMORY_FOLDER, safeSeverName, safeChannelName);
if (fs.existsSync(channelFolder)) {
const files = fs.readdirSync(channelFolder)
.filter(file => file.startsWith('raw_prompt_'))
.map(file => path.join(channelFolder, file));
files.forEach(file => {
fs.unlinkSync(file);
logger.info(`Removed old raw prompt file: ${file}`);
});
}
}
}
});
}
client.on('ready', () => {
logger.success(`Connected as ${client.user.tag}`);
// Set up an interval to regularly check inactive channels (only if timeout is enabled)
if (INACTIVITY_TIMEOUT > 0) {
setInterval(checkInactiveChannels, 60000); // Check every minute
logger.info(`Inactivity checker initialized (${INACTIVITY_TIMEOUT_MINUTES} minute timeout)`);
} else {
logger.info('Inactivity checker disabled - infinite memory mode');
}
logger.separator();
});
// Listen for ALL messages to build channel history
client.on('messageCreate', async (msg) => {
// Skip bot messages and system messages
if (msg.author.bot || msg.system) return;
if (USE_HISTORY_CONVERSATION) {
const channelId = msg.channel.id;
// Initialize channel message history if needed
if (!channelMessageHistory.has(channelId)) {
channelMessageHistory.set(channelId, []);
}
const messageHistory = channelMessageHistory.get(channelId);
// Add message to history
messageHistory.push({
author: msg.author.username,
content: msg.content,
timestamp: msg.createdAt,
id: msg.id
});
// Limit history size per channel
if (messageHistory.length > NB_MESSAGES_HISTORY) {
messageHistory.shift(); // Remove oldest message
}
}
});
// Listen for incoming messages (mentions only for bot responses)
client.on('messageCreate', async (message) => {
if (!message.mentions.has(client.user.id) || message.author.id === client.user.id) return;
// last activity
const channelId = message.channel.id;
lastActivityTime.set(channelId, Date.now());
logger.separator();
logger.info(`Received mention from ${message.author.username} in channel ${'#' + message.channel.name || 'DM'}`);
logger.info(`Message content: "${message.content}"`);
try {
// Check if the bot has permission to send messages in the channel
const hasPermission = canSendMessages(message.channel);
// If the bot doesn't have permission, log a warning and exit early
if (!hasPermission) {
logger.warn(`No permission to send messages in channel #${message.channel.name || 'DM'} - skipping Ollama API call`);
logger.separator();
return; // Exit early to avoid unnecessary API call
}
// Show typing indicator
message.channel.sendTyping().catch(err => {
if (err.code === 50001) {
logger.warn(`No permission to show typing in channel #${message.channel.name || 'DM'}`);
} else {
logger.error(`Failed to send typing indicator: ${err.message}`);
}
});
logger.info('Started typing indicator');
// Get or initialize channel history
const channelId = message.channel.id;
if (!conversationHistory.has(channelId)) {
logger.info(`Initializing new conversation history for channel ${message.channel.name || 'DM'}`);
conversationHistory.set(channelId, []);
} const history = conversationHistory.get(channelId);
const messages = [
{
role: "system",
content: BOT_CONTEXT
}
];
// Add recent channel message history if enabled
if (USE_HISTORY_CONVERSATION && channelMessageHistory.has(channelId)) {
const recentMessages = channelMessageHistory.get(channelId);
if (recentMessages.length > 0) {
logger.info(`Adding ${recentMessages.length} recent messages from channel history`);
recentMessages.forEach((msg) => {
// Don't add the current message again (it will be added later)
if (msg.id !== message.id) {
messages.push({
role: "user",
content: `${msg.author}: ${msg.content}`
});
}
});
}
}
// Add bot conversation history as proper chat messages if available
if (history.length > 0) {
history.forEach((entry) => {
if (entry.author === client.user.username) {
messages.push({
role: "assistant",
content: entry.content
});
} else {
messages.push({
role: "user",
content: `${entry.author}: ${entry.content}`
});
}
});
}
// Add current message
messages.push({
role: "user",
content: `${message.author.username}: ${message.content}`
});
// Prepare the full prompt
let fullPrompt = "";
// Add recent channel message history if enabled
if (USE_HISTORY_CONVERSATION && channelMessageHistory.has(channelId)) {
const recentMessages = channelMessageHistory.get(channelId);
if (recentMessages.length > 0) {
fullPrompt += "Recent channel conversation:\n";
recentMessages.forEach((msg) => {
// Don't add the current message again
if (msg.id !== message.id) {
fullPrompt += `${msg.author}: ${msg.content}\n`;
}
});
fullPrompt += "\n";
}
}
// Add bot conversation history if available
if (history.length > 0) {
fullPrompt += "Previous conversation with bot:\n";
history.forEach((entry) => {
fullPrompt += `${entry.author}: ${entry.content}\n`;
});
fullPrompt += "\n";
}
// Add current message
fullPrompt += `${message.author.username} (ping: ${message.author.id}) say : ${message.content}\n\n`;
// Prepare request to Ollama
const payload = {
model: MODEL,
messages: messages,
stream: false
};
logger.info(`Sending request to Ollama API with model: ${MODEL || 'default'}`);
// Use the typing indicator function to keep showing "typing..." during API call
const response = await showTypingUntilDone(message.channel, async () => {
return await axios.post(OLLAMA_API_URL, payload, {
headers: { 'Content-Type': 'application/json' }
});
});
logger.success(`Received response from Ollama`);
if (DEBUG_MODE) {
logger.info('=== DEBUG: Full Ollama Response ===');
console.log(JSON.stringify(response.data, null, 2));
logger.info('=== END DEBUG ===');
}
lastActivityTime.set(channelId, Date.now());
let generatedResponse = response.data.message.content;
// Format <think> tags as quotes
generatedResponse = formatThinkTags(generatedResponse);
// Truncate (if >2000 characters)
generatedResponse = truncateMessage(generatedResponse);
if (generatedResponse.length > 200) {
logger.info(`Generated response: "${generatedResponse.substring(0, 200)}..."`);
} else {
logger.info(`Generated response: "${generatedResponse}"`);
}
// Reply in the same channel
try {
logger.info(`Sending reply to channel ${message.channel.name || 'DM'}`);
await message.reply(generatedResponse);
} catch (replyError) {
if (replyError.code === 50001 || replyError.code === 50013) {
logger.warn(`Cannot reply in channel #${message.channel.name || 'DM'} due to missing permissions`);
logger.info(`Generated response that couldn't be delivered: "${generatedResponse.substring(0, 200)}${generatedResponse.length > 200 ? '...' : ''}"`);
} else {
throw replyError;
}
}
// Update history
history.push({ author: message.author.username, content: message.content });
history.push({ author: client.user.username, content: generatedResponse });
// Limit history size
if (history.length > HISTORY_LIMIT * 2) { // *2 because we store question/answer pairs
logger.info(`Trimming conversation history for channel ${message.channel.name || 'DM'}`);
history.splice(0, 2); // Delete the oldest question/answer pair
}
saveMemoryToFile(
fullPrompt,
message.guild ? message.guild.name : 'DirectMessages',
message.channel.name || 'direct',
message.author.username
);
logConversation({
userId: message.author.id,
username: message.author.username,
guildName: message.guild ? message.guild.name : null,
channelName: message.channel.name,
channelId: message.channel.id,
content: message.content
}, generatedResponse);
} catch (error) {
logger.error(`Error calling Ollama: ${error.message}`);
if (error.response) {
logger.error(`Response status: ${error.response.status}`);
logger.error(`Response data: ${JSON.stringify(error.response.data)}`);
}
await message.reply("Sorry, I encountered an error while processing your request.");
}
logger.separator();
});
/******************************/
// Log conversations to file
/*******************************/
function logConversation(userData, botResponse) {
if (!LOG_CONVERSATIONS) return;
try {
// Create log entry
const logEntry = {
timestamp: new Date().toISOString(),
user: {
id: userData.userId,
username: userData.username,
discriminator: userData.discriminator
},
server: userData.guildName || 'Direct Message',
channel: userData.channelName || 'DM',
channelId: userData.channelId,
userMessage: userData.content,
botResponse: botResponse,
};
// Check if the log file exists and read it
let logs = [];
if (fs.existsSync(LOGS_FILE_PATH)) {
try {
const fileContent = fs.readFileSync(LOGS_FILE_PATH, 'utf8');
logs = JSON.parse(fileContent);
// Check if the logs are an array
if (!Array.isArray(logs)) {
logger.warn('Le fichier de logs n\'est pas un tableau valide, création d\'un nouveau');
logs = [];
}
} catch (parseError) {
logger.error(`Erreur lors de la lecture du fichier de logs: ${parseError.message}`);
logger.info('Création d\'un nouveau fichier de logs');
logs = [];
}
}
// Add the new log entry to the logs array
logs.push(logEntry);
// Write the updated logs back to the file
fs.writeFileSync(LOGS_FILE_PATH, JSON.stringify(logs, null, 2), 'utf8');
logger.info(`Conversation logged to ${LOGS_FILE_PATH}`);
} catch (error) {
logger.error(`Error logging conversation: ${error.message}`);
}
}
/******************************/
// Save memory to file (FOR DEBUGGING)
/*******************************/
function saveMemoryToFile(fullPrompt, serverName, channelName, authorUsername) {
if (!DEBUG_MODE) return;
try {
// Assurez-vous que fullPrompt est une chaîne
if (typeof fullPrompt !== 'string') {
fullPrompt = String(fullPrompt || '');
logger.warn('fullPrompt n\'est pas une chaîne, conversion forcée');
}
// Sanitiser les noms pour les chemins de fichier
const sanitizeForPath = name => {
if (typeof name !== 'string') {
name = String(name || '');
}
return name.replace(/[\\/:*?"<>|]/g, '_').trim();
};
const safeSeverName = sanitizeForPath(serverName || 'UnknownServer');
const safeChannelName = sanitizeForPath(channelName || 'UnknownChannel');
const safeAuthorName = sanitizeForPath(authorUsername || 'unknown');
// Créer le format d'heure hhmmss
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const seconds = String(now.getSeconds()).padStart(2, '0');
const timestamp = `${hours}${minutes}${seconds}`;
// Créer les dossiers s'ils n'existent pas
const serverFolder = path.join(MEMORY_FOLDER, safeSeverName);
if (!fs.existsSync(serverFolder)) {
fs.mkdirSync(serverFolder, { recursive: true });
}
const channelFolder = path.join(serverFolder, safeChannelName);
if (!fs.existsSync(channelFolder)) {
fs.mkdirSync(channelFolder, { recursive: true });
}
// Créer le nom de fichier avec le nom de l'auteur
const filename = `raw_prompt_${safeAuthorName}_${timestamp}.txt`;
const filePath = path.join(channelFolder, filename);
// Écrire le prompt brut dans le fichier
fs.writeFileSync(filePath, fullPrompt, 'utf8');
logger.info(`Raw prompt saved to ${safeSeverName}/${safeChannelName}/${filename}`);
// Limiter le nombre de fichiers
const files = fs.readdirSync(channelFolder)
.filter(file => file.startsWith('raw_prompt_'))
.map(file => ({
name: file,
path: path.join(channelFolder, file),
time: fs.statSync(path.join(channelFolder, file)).mtime.getTime()
}))
.sort((a, b) => b.time - a.time); // Tri par date décroissante
if (files.length > HISTORY_LIMIT) {
for (let i = HISTORY_LIMIT; i < files.length; i++) {
fs.unlinkSync(files[i].path);
logger.info(`Removed old raw prompt file: ${files[i].name}`);
}
}
return filePath;
} catch (error) {
logger.error(`Error saving raw prompt: ${error.message}`);
return null;
}
}
client.login(MY_TOKEN)
.then(() => logger.info('Login process started'))
.catch(err => logger.error(`Failed to login: ${err.message}`));