Merge pull request 'Some more changed to the bot structure' (#2) from MiTask/LinkUp-P2P-Chat:main into main

Reviewed-on: snxraven/LinkUp-P2P-Chat#2
This commit is contained in:
snxraven 2024-06-08 21:11:17 +00:00
commit cc654112b2
2 changed files with 17 additions and 10 deletions

View File

@ -57,14 +57,14 @@ loadCommands().then(commands => {
commandHandler.handler(bot, args, message); commandHandler.handler(bot, args, message);
} }
} }
}) });
bot.joinChatRoom();
// Wait for 2 seconds for the bot to connect bot.on('onBotJoinRoom', () => {
setTimeout(() => { console.log("Bot is ready!");
// Send a message
bot.sendMessage(process.env.ON_READY_MESSAGE); bot.sendMessage(process.env.ON_READY_MESSAGE);
}, 2000); // Adjust the delay as necessary });
bot.joinChatRoom();
}).catch(error => { }).catch(error => {
console.error('Error loading commands:', error); console.error('Error loading commands:', error);
}); });

View File

@ -4,6 +4,9 @@ import EventEmitter from 'node:events'
class Client extends EventEmitter { class Client extends EventEmitter {
constructor(chatRoomID, botName) { constructor(chatRoomID, botName) {
super(); super();
if(!chatRoomID || !botName) return console.error("ChatRoomID or BotName is not defined!");
this.topicBuffer = Buffer.from(chatRoomID, 'hex'); this.topicBuffer = Buffer.from(chatRoomID, 'hex');
this.botName = botName; this.botName = botName;
this.swarm = new Hyperswarm(); this.swarm = new Hyperswarm();
@ -12,8 +15,11 @@ class Client extends EventEmitter {
setupSwarm() { setupSwarm() {
this.swarm.on('connection', (peer) => { this.swarm.on('connection', (peer) => {
peer.on('data', message => this.emit("onMessage", peer, JSON.parse(message.toString()))); peer.on('data', message => this.emit('onMessage', peer, JSON.parse(message.toString())));
peer.on('error', e => console.log(`Connection error: ${e}`)); peer.on('error', e => {
this.emit('onError', e);
console.error(`Connection error: ${e}`)
});
}); });
this.swarm.on('update', () => { this.swarm.on('update', () => {
@ -25,6 +31,7 @@ class Client extends EventEmitter {
this.discovery = this.swarm.join(this.topicBuffer, {client: true, server: true}); this.discovery = this.swarm.join(this.topicBuffer, {client: true, server: true});
this.discovery.flushed().then(() => { this.discovery.flushed().then(() => {
console.log(`Bot ${this.botName} joined the chat room.`); console.log(`Bot ${this.botName} joined the chat room.`);
this.emit('onBotJoinRoom');
}); });
} }