LinkUp-P2P-Chat/chatBot/includes/client.js
2024-06-08 23:38:44 +03:00

53 lines
1.5 KiB
JavaScript

import Hyperswarm from 'hyperswarm';
import EventEmitter from 'node:events'
class Client extends EventEmitter {
constructor(chatRoomID, botName) {
super();
if(!chatRoomID || !botName) return console.error("ChatRoomID or BotName is not defined!");
this.topicBuffer = Buffer.from(chatRoomID, 'hex');
this.botName = botName;
this.swarm = new Hyperswarm();
this.setupSwarm();
}
setupSwarm() {
this.swarm.on('connection', (peer) => {
peer.on('data', message => this.emit('onMessage', peer, JSON.parse(message.toString())));
peer.on('error', e => {
this.emit('onError', e);
console.error(`Connection error: ${e}`)
});
});
this.swarm.on('update', () => {
console.log(`Peers count: ${this.swarm.connections.size}`);
});
}
joinChatRoom() {
this.discovery = this.swarm.join(this.topicBuffer, {client: true, server: true});
this.discovery.flushed().then(() => {
console.log(`Bot ${this.botName} joined the chat room.`);
this.emit('onBotJoinRoom');
});
}
sendMessage(message) {
console.log('Bot name:', this.botName);
const timestamp = Date.now(); // Generate timestamp
const peers = [...this.swarm.connections];
const data = JSON.stringify({name: this.botName, message, timestamp}); // Include timestamp
for (const peer of peers) peer.write(data);
}
destroy() {
this.swarm.destroy();
console.log(`Bot ${this.botName} disconnected.`);
}
}
export default Client;