From 404f440f48dda064a481f5ca812d9aa16fa83b4e Mon Sep 17 00:00:00 2001 From: Sharon Kennedy Date: Wed, 1 Jul 2020 00:51:29 -0400 Subject: [PATCH] wait for initial sync before adding listeners --- src/bot.js | 43 +++++++++++++++++++++++++++---------------- 1 file changed, 27 insertions(+), 16 deletions(-) diff --git a/src/bot.js b/src/bot.js index 5e28fa7..bb0806d 100644 --- a/src/bot.js +++ b/src/bot.js @@ -81,7 +81,7 @@ class OcrccBot { }); await this.sendMessage(roomId, content); default: - logger.log("error", `ERROR SENDING MESSAGE: ${err}`); + logger.log("error", `ERROR SENDING MESSAGE ${content.body}: ${err}`); break; } } @@ -474,26 +474,31 @@ class OcrccBot { member.membership === "leave" && member.userId !== this.config.BOT_USERID ) { - const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`) - if (member.userId === facilitatorId) { - this.sendTextMessage( - member.roomId, - `${member.name} has left the chat.` - ); - } + // ensure bot is still in the room + const roomData = await this.client.getJoinedRooms() + const joinedRooms = roomData["joined_rooms"] + const isBotInRoom = joinedRooms.includes(member.roomId) - // leave if there is nobody in the room const room = this.client.getRoom(member.roomId) if (!room) return + // leave if there is nobody in the room const memberCount = room.getJoinedMemberCount() - - if (memberCount === 1) { // just the bot left + if (memberCount === 1 && isBotInRoom) { // just the bot left logger.log("info", `LEAVING EMPTY ROOM ==> ${member.roomId}`); this.deleteTranscript(member.userId, member.roomId); this.localStorage.removeItem(`${member.roomId}-facilitator`) this.localStorage.removeItem(`${member.roomId}-transcript`) - this.client.leave(member.roomId) + return this.client.leave(member.roomId) + } + + // notify room if the facilitator has left + const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`) + if (isBotInRoom && member.userId === facilitatorId) { + this.sendTextMessage( + member.roomId, + `${member.name} has left the chat.` + ); } } }) @@ -551,12 +556,18 @@ class OcrccBot { }; this.client = matrix.createClient(opts); - await this.deleteOldDevices() - await this.trackJoinedRooms() await this.client.initCrypto() - await this.setMembershipListeners(); - await this.setMessageListeners(); this.client.startClient({ initialSyncLimit: 0 }) + + this.client.once('sync', async (state, prevState, data) => { + logger.log("info", `SYNC STATUS: ${state}`) + if (state === 'PREPARED') { + await this.deleteOldDevices() + await this.trackJoinedRooms() + await this.setMembershipListeners(); + await this.setMessageListeners(); + } + }); } catch(err) { this.handleBotCrash(undefined, err); logger.log("error", `ERROR INITIALIZING CLIENT: ${err}`);