ai-discord-bot/events/messageCreate.js
Bildcraft1 74b3f53212 chore: Refactor message processing logic and split output into chunks
Refactor the `process_message` function in `bot.py` to improve performance and handle longer messages. The function now appends extra characters to the base message to ensure it is always 4000 characters long. This change improves the processing of messages and prevents truncation.

In `messageCreate.js`, split the output into chunks of 2000 characters using the `splitMessage` function. This allows sending each part as a separate message, ensuring that the output is not cut off.
2024-06-06 10:19:06 +02:00

72 lines
No EOL
3.2 KiB
JavaScript

const { Events } = require('discord.js');
const fs = require('fs');
const { exec } = require('child_process');
const { logAction } = require('../logs/logger.js'); // Import logAction
module.exports = {
name: Events.MessageCreate,
async execute(message) {
// Ignore messages sent by the bot itself
if (message.author.bot) return;
const config = JSON.parse(fs.readFileSync('config.json', 'utf-8'));
// Check if the message is a DM or if the bot is mentioned in a guild message
const isDM = message.guild === null;
const isMentioned = message.mentions.has(message.client.user);
if (isDM || isMentioned) {
// Get the content of the message and remove the bot mention if in a guild
const botMention = isDM ? '' : `<@${message.client.user.id}>`;
const messageContent = message.content.replace(botMention, '').trim();
// Log the message
console.log(`[LOG] User ${message.author.tag} asked: ${messageContent}`);
logAction(`${message.author.tag}: ${messageContent}`, message.author.id, message.author.tag);
if (config.whitelist.includes(message.author.id)) {
exec(`python3 bot.py "${messageContent}"`, (error, stdout, stderr) => {
if (error) {
console.error(`Error executing script: ${error.message}`);
logAction(`GPT: ${error.message}`, message.author.id, message.author.tag);
return message.reply("There was an error processing your request.");
}
if (stderr) {
console.error(`Script error: ${stderr}`);
logAction(`GPT: ${stderr}`, message.author.id, message.author.tag);
return message.reply("There was an error processing your request.");
}
let output = stdout.trim();
// Log the output from the Python script
logAction(`GPT: ${output}`, message.author.id, message.author.tag);
// Function to split the output into chunks of 2000 characters
function splitMessage(message, maxLength) {
const parts = [];
while (message.length > 0) {
if (message.length > maxLength) {
parts.push(message.slice(0, maxLength));
message = message.slice(maxLength);
} else {
parts.push(message);
message = '';
}
}
return parts;
}
// Split the output if it's longer than 2000 characters
const maxMessageLength = 2000;
const messageParts = splitMessage(output, maxMessageLength);
// Send each part as a separate message
messageParts.forEach(part => message.reply(part));
});
} else {
message.reply("Not whitelisted");
}
}
},
}