ai-discord-bot/events/messageCreate.js

51 lines
2.3 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.");
}
// Log the output from the Python script
logAction(`GPT: ${stdout.trim()}`, message.author.id, message.author.tag);
// Reply with the output from the Python script
message.reply(stdout.trim());
});
} else {
message.reply("Not whitelisted");
}
}
},
};