forked from snxraven/LinkUp-P2P-Chat
73 lines
2.4 KiB
JavaScript
73 lines
2.4 KiB
JavaScript
import fs from 'fs';
|
|
import path from 'path';
|
|
import Client from './includes/Client.js'; // Adjust the import path as necessary
|
|
import 'dotenv/config';
|
|
|
|
// Create a new instance of the chatBot class with a valid botName
|
|
const botName = process.env.BOT_NAME; // Replace 'MyBot' with the desired bot name
|
|
const linkupRoomId = process.env.LINKUP_ROOM_ID; // Use the environment variable for room ID
|
|
|
|
// Load commands from the 'commands' directory
|
|
const commandsDir = path.join(new URL('./commands/', import.meta.url).pathname);
|
|
|
|
async function loadCommands() {
|
|
const commands = {};
|
|
|
|
// Read files from the commands directory
|
|
const files = await fs.promises.readdir(commandsDir);
|
|
|
|
// Iterate through each file
|
|
for (const file of files) {
|
|
// Check if the file is a JavaScript file
|
|
if (file.endsWith('.js')) {
|
|
const commandName = path.basename(file, '.js');
|
|
const commandPath = path.join(commandsDir, file);
|
|
|
|
// Dynamically import the command module
|
|
const { default: commandModule } = await import(commandPath);
|
|
|
|
// Add the command module to the commands object
|
|
commands[commandName] = commandModule;
|
|
}
|
|
}
|
|
|
|
return commands;
|
|
}
|
|
|
|
loadCommands().then(commands => {
|
|
// Create the chatBot instance with the defined onMessageReceived function
|
|
const bot = new Client(botName);
|
|
|
|
// We use Event Emitter here to handle new messages
|
|
bot.on('onMessage', (peer, message) => {
|
|
console.log(message);
|
|
|
|
console.log(`Message received from ${message.peerName}@${message.topic} at ${new Date(message.timestamp).toLocaleTimeString()}: ${message.message}`);
|
|
|
|
// Handle all messages as potential AI commands
|
|
const userMessage = message.message;
|
|
|
|
// Find the corresponding command handler (assuming the AI command handler is in 'commands/ai.js')
|
|
const commandHandler = commands['ai'];
|
|
|
|
// If the command exists, execute its handler
|
|
if (commandHandler && typeof commandHandler.handler === 'function') {
|
|
commandHandler.handler(bot, [userMessage], message);
|
|
}
|
|
});
|
|
|
|
bot.on('onBotJoinRoom', () => {
|
|
console.log("Bot is ready!");
|
|
// Include topic in the message sent when the bot joins the room
|
|
bot.sendTextMessage({
|
|
text: process.env.ON_READY_MESSAGE,
|
|
topic: linkupRoomId
|
|
});
|
|
});
|
|
|
|
// Ensure the bot joins the chat room with the topic information
|
|
bot.joinChatRoom(linkupRoomId);
|
|
}).catch(error => {
|
|
console.error('Error loading commands:', error);
|
|
});
|