40 lines
No EOL
1.3 KiB
JavaScript
40 lines
No EOL
1.3 KiB
JavaScript
// states/HandleChat.js
|
||
const path = require('path');
|
||
const fs = require('fs');
|
||
const { getLastChat, getBot, getDB } = require('../core/context');
|
||
const { logChatMessage } = require('../memory/chat');
|
||
const { chatWithAI } = require('../lib/ai-helper');
|
||
const config = require('../config.json');
|
||
|
||
module.exports = async function HandleChat() {
|
||
const bot = getBot();
|
||
const db = getDB();
|
||
const { username, message } = getLastChat();
|
||
const msg = message.toLowerCase();
|
||
|
||
console.log(`[STATE] HandleChat: ${message}`);
|
||
logChatMessage(db, username, message);
|
||
|
||
// Load available task scripts from the task directory.
|
||
const taskDir = path.join(__dirname, '../bot-tasks');
|
||
const availableTasks = fs.readdirSync(taskDir)
|
||
.filter(f => f.endsWith('.js'))
|
||
.map(f => f.replace('.js', ''));
|
||
|
||
const matchedTask = availableTasks.find(task => msg.includes(task.replace(/-/g, ' ')));
|
||
|
||
if (matchedTask) {
|
||
try {
|
||
const task = require(path.join(taskDir, matchedTask));
|
||
bot.chat(`Okay, I’ll try to ${matchedTask.replace(/-/g, ' ')}.`);
|
||
await task();
|
||
return;
|
||
} catch (err) {
|
||
console.error(`[TASK ERROR] ${matchedTask}:`, err.message);
|
||
bot.chat(`I couldn't complete the task "${matchedTask}".`);
|
||
}
|
||
}
|
||
|
||
const response = await chatWithAI(message, config.ai);
|
||
bot.chat(response);
|
||
}; |