cletus/bot/states/HandleChat.js
roberts d8a907dc63
All checks were successful
Deploy Cletus Bot / deploy (push) Successful in 26s
Updated Idle and HandleChat.
2025-05-10 19:28:56 -05:00

60 lines
No EOL
2.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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));
const { setActiveTask, clearActiveTask } = require('../core/context');
setActiveTask(matchedTask);
bot.chat(`Okay, Ill try to ${matchedTask.replace(/-/g, ' ')}.`);
await task(bot, db, bot.chat);
clearActiveTask();
return;
} catch (err) {
console.error(`[TASK ERROR] ${matchedTask}:`, err.message);
bot.chat(`I couldn't complete the task "${matchedTask}".`);
}
}
if (!matchedTask) {
const prompt = `Player said: "${message}". If this is a command, what task name (like 'find-flower', 'chop-tree') would you execute? Otherwise, reply "none".`;
const aiResponse = await chatWithAI(prompt, config.ai);
const aiTask = aiResponse.trim().toLowerCase().replace(/\s+/g, '-');
if (availableTasks.includes(aiTask)) {
const task = require(path.join(taskDir, aiTask));
bot.chat(`Okay, Ill try to ${aiTask.replace(/-/g, ' ')}.`);
setActiveTask(aiTask);
await task(bot, db, bot.chat);
clearActiveTask();
return;
}
}
if (msg.includes(bot.username.toLowerCase())) {
const response = await chatWithAI(message, config.ai);
bot.chat(response);
}
};