forked from snxraven/LinkUp-P2P-Chat
first commit
This commit is contained in:
44
chatBot/includes/chatBot.js
Normal file
44
chatBot/includes/chatBot.js
Normal file
@ -0,0 +1,44 @@
|
||||
import Hyperswarm from 'hyperswarm';
|
||||
|
||||
class chatBot {
|
||||
constructor(topicBuffer, botName, onMessageReceived) {
|
||||
this.topicBuffer = topicBuffer;
|
||||
this.botName = botName;
|
||||
this.swarm = new Hyperswarm();
|
||||
this.onMessageReceived = onMessageReceived;
|
||||
this.setupSwarm();
|
||||
}
|
||||
|
||||
setupSwarm() {
|
||||
this.swarm.on('connection', (peer) => {
|
||||
peer.on('data', message => this.onMessageReceived(peer, JSON.parse(message.toString())));
|
||||
peer.on('error', e => console.log(`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.`);
|
||||
});
|
||||
}
|
||||
|
||||
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 chatBot;
|
Reference in New Issue
Block a user