LinkUp-P2P-Chat/chatBot/bot.js

69 lines
2.2 KiB
JavaScript
Raw Normal View History

2024-06-04 01:19:56 -04:00
import fs from 'fs';
import path from 'path';
import Client from './includes/Client.js'; // Adjust the import path as necessary
import 'dotenv/config';
2024-06-03 19:23:14 -04:00
// 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
2024-06-04 01:19:56 -04:00
// 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')) {
2024-06-14 09:43:17 -04:00
// const commandName = path.basename(file, '.js');
2024-06-04 01:19:56 -04:00
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
2024-06-14 09:43:17 -04:00
commands[commandPath] = commandModule;
2024-06-04 01:19:56 -04:00
}
2024-06-03 19:23:14 -04:00
}
2024-06-04 01:19:56 -04:00
return commands;
2024-06-03 19:23:14 -04:00
}
2024-06-04 01:19:56 -04:00
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) => {
2024-06-04 01:19:56 -04:00
console.log(message);
2024-06-14 04:46:19 -04:00
console.log(`Message received from ${message.peerName}@${message.topic} at ${new Date(message.timestamp).toLocaleTimeString()}: ${message.message}`);
2024-06-04 01:19:56 -04:00
2024-06-13 20:47:45 -04:00
// Check if the message starts with a command prefix
if (message.message.startsWith('!')) {
// Extract the command and arguments
const [command, ...args] = message.message.slice(1).split(' ');
2024-06-04 01:19:56 -04:00
2024-06-13 20:47:45 -04:00
// Find the corresponding command handler
const commandHandler = commands[command.toLowerCase()];
2024-06-04 01:19:56 -04:00
2024-06-13 20:47:45 -04:00
// If the command exists, execute its handler
if (commandHandler && typeof commandHandler.handler === 'function') {
commandHandler.handler(bot, args, message);
}
2024-06-04 01:19:56 -04:00
}
2024-06-08 16:29:51 -04:00
});
bot.on('onBotJoinRoom', () => {
2024-06-08 16:29:51 -04:00
console.log("Bot is ready!");
2024-06-13 20:47:45 -04:00
bot.sendTextMessage(process.env.ON_READY_MESSAGE);
2024-06-08 16:29:51 -04:00
});
2024-06-13 20:47:45 -04:00
bot.joinChatRoom(process.env.LINKUP_ROOM_ID);
2024-06-04 01:19:56 -04:00
}).catch(error => {
console.error('Error loading commands:', error);
2024-06-13 20:47:45 -04:00
});