Some more changed to the bot structure #2

Merged
snxraven merged 5 commits from MiTask/LinkUp-P2P-Chat:main into main 2024-06-08 17:11:17 -04:00
2 changed files with 20 additions and 5 deletions
Showing only changes of commit b244aa9bdf - Show all commits

View File

@ -38,7 +38,7 @@ loadCommands().then(commands => {
const bot = new Client(process.env.LINKUP_ROOM_ID, botName);
// We use Event Emitter here to handle new messages
bot.on('onMessage', (peer, message) => {
bot.on(Event.onMessage, (peer, message) => {
if (message.type == "icon") return;
console.log(message);
@ -57,7 +57,12 @@ loadCommands().then(commands => {
commandHandler.handler(bot, args, message);
}
}
})
});
bot.on(Event.onBotJoinRoom, () => {
console.log("Bot is ready!");
});
bot.joinChatRoom();
// Wait for 2 seconds for the bot to connect

View File

@ -12,8 +12,11 @@ class Client extends EventEmitter {
setupSwarm() {
this.swarm.on('connection', (peer) => {
peer.on('data', message => this.emit("onMessage", peer, JSON.parse(message.toString())));
peer.on('error', e => console.log(`Connection error: ${e}`));
peer.on('data', message => this.emit(Event.onMessage, peer, JSON.parse(message.toString())));
peer.on('error', e => {
this.emit(Event.onError, e);
console.error(`Connection error: ${e}`)
});
});
this.swarm.on('update', () => {
@ -24,6 +27,7 @@ class Client extends EventEmitter {
joinChatRoom() {
this.discovery = this.swarm.join(this.topicBuffer, { client: true, server: true });
this.discovery.flushed().then(() => {
this.emit(Event.onBotJoinRoom)
console.log(`Bot ${this.botName} joined the chat room.`);
});
}
@ -42,4 +46,10 @@ class Client extends EventEmitter {
}
}
export default Client;
enum Event {
onMessage,
onError,
onBotJoinRoom
}
export default { Client, Event };