15 Commits

Author SHA1 Message Date
Sharon Kennedy
687dfa84e9 2.0.2 2020-09-11 16:29:31 -04:00
Sharon Kennedy
b7da515969 Merge branch 'master' of github.com:nomadic-labs/ocrcc-bot 2020-09-11 16:29:08 -04:00
Sharon Kennedy
e2c291c040 change notice to signal 2020-09-11 16:12:01 -04:00
brent
87f2c5290f add timezone to dockerfile 2020-09-08 10:41:29 -04:00
Sharon Kennedy
4fdddc8c92 2.0.1 2020-09-07 12:00:16 -04:00
Sharon Kennedy
d53a5c5e26 change order of statements when handling member leaving to avoid sending close signal twice 2020-09-07 11:54:05 -04:00
brent
9772b3b1fd different strategy for python dependencies 2020-09-06 17:47:05 -04:00
brent
84fe91adbb new attempt at python install 2020-09-06 17:38:57 -04:00
brent
b6cd85eab0 removed parameters from python install 2020-09-06 17:33:12 -04:00
brent
209b3aaa45 removed sudo 2020-09-06 17:28:23 -04:00
edwardsbrentg
4912ce6f61 Merge pull request #3 from nomadic-labs/install-python-dockerfile
add python installation to dockerfile
2020-09-06 17:22:13 -04:00
brent
013ffa318f add python installation to dockerfile 2020-09-06 17:20:49 -04:00
Sharon Kennedy
ac2f953b90 2.0.0 2020-09-06 14:07:50 -04:00
Sharon Kennedy
a25c71a04a latest build 2020-09-06 14:07:44 -04:00
Sharon
836d4751ad Merge pull request #2 from nomadic-labs/botsignal
Move timeouts to bot and use custom event to signal clients to close
2020-09-06 14:06:28 -04:00
7 changed files with 256 additions and 165 deletions

View File

@@ -1,5 +1,10 @@
FROM node:10-alpine
RUN apk add g++ make python
RUN apk add tzdata
ENV TZ America/Montreal
RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app
WORKDIR /home/node/app

254
dist/bot.js vendored
View File

@@ -27,12 +27,14 @@ var _encryptAttachment = _interopRequireDefault(require("./encrypt-attachment"))
global.Olm = require("olm");
const BOT_SIGNAL_END_CHAT = 'END_CHAT';
const BOT_SIGNAL_CHAT_OFFLINE = 'CHAT_OFFLINE';
class OcrccBot {
constructor(botConfig) {
this.config = botConfig;
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
this.joinedRooms = [];
this.inactivityTimers = {};
}
createLocalStorage() {
@@ -47,20 +49,20 @@ class OcrccBot {
return new _nodeLocalstorage.LocalStorage(localStoragePath);
}
sendTextMessage(roomId, msgText, showToUser = null) {
async sendTextMessage(roomId, msgText, showToUser = null) {
const content = {
msgtype: "m.text",
body: msgText,
showToUser: showToUser
};
this.sendMessage(roomId, content);
await this.sendMessage(roomId, content);
}
async sendNotice(roomId, message) {
_logger.default.log("info", `SENDING *NOTICE*: ${message}`);
try {
await this.client.sendNotice(roomId, message);
_logger.default.log("info", `SENT *NOTICE*: ${message}`);
} catch (err) {
switch (err["name"]) {
case "UnknownDeviceError":
@@ -129,10 +131,9 @@ class OcrccBot {
}
async inviteFacilitators(roomId) {
this.localStorage.setItem(`${roomId}-waiting`, 'true');
let invitations = [];
try {
this.localStorage.setItem(`${roomId}-waiting`, 'true');
let invitations = [];
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
const members = Object.keys(roomMembers["joined"]);
members.forEach(memberId => {
@@ -149,7 +150,7 @@ class OcrccBot {
} else {
_logger.default.log('info', "NO FACILITATORS ONLINE");
this.sendNotice(roomId, "CHAT_OFFLINE");
this.sendBotSignal(roomId, BOT_SIGNAL_CHAT_OFFLINE);
}
} catch (err) {
this.handleBotCrash(roomId, err);
@@ -159,9 +160,8 @@ class OcrccBot {
}
async uninviteFacilitators(roomId) {
this.localStorage.removeItem(`${roomId}-waiting`);
try {
this.localStorage.removeItem(`${roomId}-waiting`);
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId);
const roomMembersIds = Object.keys(supportRoomMembers["joined"]);
@@ -184,14 +184,23 @@ class OcrccBot {
this.sendTextMessage(roomId, this.config.BOT_ERROR_MESSAGE);
}
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, `The Help Bot ran into an error: ${error}. Please verify that the chat service is working.`);
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, `${this.config.BOT_DISPLAY_NAME} ran into an error: ${error}. Please verify that the chat service is working.`);
}
handleMessageEvent(event) {
const content = event.getContent(); // do nothing if there's no content
const content = event.getContent();
const sender = event.getSender();
const roomId = event.getRoomId(); // do nothing if there's no content
if (!content) {
return;
} // if it's a chat message and the facilitator has joined, reset the inactivity timeout
const facilitatorId = this.localStorage.getItem(`${roomId}-facilitator`);
if (Boolean(facilitatorId) && sender !== this.config.BOT_USERID) {
this.setInactivityTimeout(roomId);
} // bot commands
@@ -217,7 +226,7 @@ class OcrccBot {
const filepath = this.localStorage.getItem(`${roomId}-transcript`);
if (!filepath) {
return _logger.default.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}`);
return _logger.default.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}. This message will not be added: ${content.body}`);
}
const message = `${sender} [${time}]: ${content.body}\n`;
@@ -236,8 +245,9 @@ class OcrccBot {
}, {
keyword: 'delete transcript',
function: (senderId, roomId) => {
this.deleteTranscript(senderId, roomId);
}
this.deleteTranscript(senderId, roomId, true);
} // delete transcript and send confirmation message
}, {
keyword: 'say',
function: (senderId, roomId, message) => {
@@ -270,7 +280,7 @@ class OcrccBot {
}
}
async leaveEmptyRooms(senderId) {
async leaveEmptyRooms() {
try {
const roomData = await this.client.getJoinedRooms();
const joinedRoomsIds = roomData["joined_rooms"];
@@ -279,16 +289,16 @@ class OcrccBot {
if (room && room.getJoinedMemberCount() === 1) {
try {
_logger.default.log('info', "LEAVING EMPTY ROOM => " + roomId);
await this.client.leave(roomId);
_logger.default.log('info', `LEAVING EMPTY ROOM => ${roomId}`);
} catch (err) {
_logger.default.log('error', "ERROR LEAVING EMPTY ROOM => " + err);
_logger.default.log('error', `ERROR LEAVING ROOM ${roomId} => ${err}`);
}
}
});
} catch (err) {
_logger.default.log("error", `ERROR GETTING JOINED ROOMS: ${err}`);
_logger.default.log("error", `ERROR LEAVING EMPTY ROOMS: ${err}`);
}
}
@@ -297,7 +307,7 @@ class OcrccBot {
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
if (!transcriptFile) {
this.sendTextMessage(roomId, "There is no transcript for this chat.", senderId);
this.sendTextMessage(roomId, "Cannot send transcript, there is no transcript for this chat.", senderId);
}
if (this.client.isRoomEncrypted(roomId)) {
@@ -356,11 +366,11 @@ class OcrccBot {
}
}
deleteTranscript(senderId, roomId) {
deleteTranscript(senderId, roomId, sendConfirmation = false) {
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
if (!transcriptFile) {
return this.sendTextMessage(roomId, "There is no transcript for this chat.", senderId);
return this.sendTextMessage(roomId, "Cannot delete transcript, there is no transcript for this chat.", senderId);
}
fs.unlink(transcriptFile, err => {
@@ -372,11 +382,13 @@ class OcrccBot {
return this.sendTextMessage(roomId, `There was an error deleting the transcript: ${err}`, senderId);
}
this.localStorage.removeItem(`${roomId}-transcript`);
if (sendConfirmation) {
this.sendTextMessage(roomId, `The transcript file has been deleted.`, senderId);
}
_logger.default.log('info', "DELETED TRANSCRIPT FILE => " + transcriptFile);
this.sendTextMessage(roomId, `The transcript file has been deleted.`, senderId);
this.localStorage.removeItem(`${roomId}-transcript`);
});
}
@@ -434,6 +446,7 @@ class OcrccBot {
const notification = `Incoming support chat at ${chatTime} (room ID: ${roomId})`;
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification);
this.inviteFacilitators(room.roomId);
this.setTimeoutforFacilitator(room.roomId);
}
} catch (err) {
_logger.default.log("error", "ERROR JOINING ROOM => " + err);
@@ -441,92 +454,106 @@ class OcrccBot {
}
if (member.membership === "join" && member.userId !== this.config.BOT_USERID && this.localStorage.getItem(`${member.roomId}-waiting`)) {
// make sure it's a facilitator joining
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
const members = Object.keys(roomMembers["joined"]);
const isFacilitator = members.includes(member.userId);
try {
// make sure it's a facilitator joining
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
const members = Object.keys(roomMembers["joined"]);
const isFacilitator = members.includes(member.userId);
if (isFacilitator) {
// made facilitator a moderator in the room
this.localStorage.setItem(`${member.roomId}-facilitator`, member.userId);
const event = {
getType: () => {
return "m.room.power_levels";
},
getContent: () => {
return {
users: {
[this.config.BOT_USERID]: 100,
[member.userId]: 50
}
};
}
};
this.client.setPowerLevel(member.roomId, member.userId, 50, event); // send notification to Support Chat Notifications room
const currentDate = new Date();
const chatTime = currentDate.toLocaleTimeString();
const roomId = member.roomId.split(':')[0];
const notification = `${member.name} joined the chat at ${chatTime} (room ID: ${roomId})`;
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification); // send notification to chat room
this.sendTextMessage(member.roomId, `${member.name} has joined the chat.`); // revoke the other invitations
this.uninviteFacilitators(member.roomId); // set transcript file
if (this.config.CAPTURE_TRANSCRIPTS) {
const currentDate = new Date();
const dateOpts = {
year: "numeric",
month: "short",
day: "numeric"
if (isFacilitator) {
// made facilitator a moderator in the room
this.localStorage.setItem(`${member.roomId}-facilitator`, member.userId);
const event = {
getType: () => {
return "m.room.power_levels";
},
getContent: () => {
return {
users: {
[this.config.BOT_USERID]: 100,
[member.userId]: 50
}
};
}
};
const chatDate = currentDate.toLocaleDateString("en-GB", dateOpts);
const chatTime = currentDate.toLocaleTimeString("en-GB", {
timeZone: "America/New_York"
});
const filename = `${chatDate} - ${chatTime} - ${member.roomId}.txt`;
const filepath = path.resolve(path.join("transcripts", filename));
this.localStorage.setItem(`${member.roomId}-transcript`, filepath);
this.client.setPowerLevel(member.roomId, member.userId, 50, event); // send notification to Support Chat Notifications room
const currentDate = new Date();
const chatTime = currentDate.toLocaleTimeString();
const roomId = member.roomId.split(':')[0];
const notification = `${member.name} joined the chat at ${chatTime} (room ID: ${roomId})`;
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification); // send notification to chat room
this.sendTextMessage(member.roomId, `${member.name} has joined the chat.`); // revoke the other invitations
this.uninviteFacilitators(member.roomId); // set transcript file
if (this.config.CAPTURE_TRANSCRIPTS) {
const currentDate = new Date();
const dateOpts = {
year: "numeric",
month: "short",
day: "numeric"
};
const chatDate = currentDate.toLocaleDateString("en-GB", dateOpts);
const chatTime = currentDate.toLocaleTimeString("en-GB", {
timeZone: "America/New_York"
});
const filename = `${chatDate} - ${chatTime} - ${member.roomId}.txt`;
const filepath = path.resolve(path.join("transcripts", filename));
this.localStorage.setItem(`${member.roomId}-transcript`, filepath);
}
}
} catch (err) {
_logger.default.log("error", `ERROR WHEN FACILITATOR JOINED ROOM ==> ${err}`);
}
}
if (member.membership === "leave" && member.userId !== this.config.BOT_USERID) {
// ensure bot is still in the room
const roomData = await this.client.getJoinedRooms();
const joinedRooms = roomData["joined_rooms"];
const isBotInRoom = joinedRooms.includes(member.roomId);
const room = this.client.getRoom(member.roomId);
if (!room) return; // notify room if the facilitator has left
if (!room) return;
const roomMembers = await room.getJoinedMembers(); // array
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`);
if (isBotInRoom && member.userId === facilitatorId) {
this.sendTextMessage(member.roomId, `${member.name} has left the chat.`);
} // leave if there is nobody in the room
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID); // object
const isBotInRoom = Boolean(roomMembers.find(member => member.userId === this.config.BOT_USERID)); // leave if there is nobody in the room
try {
const memberCount = room.getJoinedMemberCount();
const memberCount = roomMembers.length;
if (memberCount === 1 && isBotInRoom) {
// just the bot left
_logger.default.log("info", `LEAVING EMPTY ROOM ==> ${member.roomId}`);
_logger.default.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`);
return this.client.leave(member.roomId);
this.localStorage.removeItem(`${member.roomId}-waiting`);
return await this.client.leave(member.roomId);
}
} catch (err) {
_logger.default.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
return _logger.default.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
} // notify room if the facilitator has left
try {
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`);
if (isBotInRoom && member.userId === facilitatorId) {
this.sendTextMessage(member.roomId, `${member.name} has left the chat.`); // send notification to Support Chat Notifications room
const currentDate = new Date();
const chatTime = currentDate.toLocaleTimeString();
const roomId = member.roomId.split(':')[0];
const notification = `${member.name} left the chat at ${chatTime} (room ID: ${roomId})`;
await this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification);
}
} catch (err) {
_logger.default.log("error", `ERROR NOTIFYING THAT FACLITATOR HAS LEFT THE ROOM ==> ${err}`);
} // send signal to close the chat if there are no facilitators in the room
try {
const roomMembers = await room.getJoinedMembers();
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
const facilitators = facilitatorRoomMembers['joined'];
let facilitatorInRoom = false;
roomMembers.forEach(member => {
@@ -536,6 +563,8 @@ class OcrccBot {
});
if (!facilitatorInRoom) {
_logger.default.log("info", `NO FACILITATORS LEFT, SENDING SIGNAL TO END CHAT`);
this.sendBotSignal(member.roomId, BOT_SIGNAL_END_CHAT);
}
} catch (err) {
@@ -545,6 +574,35 @@ class OcrccBot {
});
}
setTimeoutforFacilitator(roomId) {
setTimeout(async () => {
const stillWaiting = this.localStorage.getItem(`${roomId}-waiting`);
if (stillWaiting) {
_logger.default.log("info", `FACILITATOR DID NOT JOIN CHAT WITHIN TIME LIMIT, SENDING SIGNAL TO END CHAT`);
await this.sendTextMessage(roomId, this.config.CHAT_NOT_AVAILABLE_MESSAGE);
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT);
}
}, this.config.MAX_WAIT_TIME);
}
setInactivityTimeout(roomId) {
const oldTimeout = this.inactivityTimers[roomId];
if (oldTimeout) {
clearTimeout(oldTimeout);
}
const newTimeout = setTimeout(async () => {
_logger.default.log("info", `CHAT IS INACTIVE, SENDING SIGNAL TO END CHAT`);
await this.sendTextMessage(roomId, `This chat has been closed due to inactivity.`);
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT);
}, this.config.MAX_INACTIVE);
this.inactivityTimers[roomId] = newTimeout;
}
async setMessageListeners() {
// encrypted messages
this.client.on("Event.decrypted", (event, err) => {
@@ -564,30 +622,23 @@ class OcrccBot {
});
}
async leaveOldRooms() {
const roomData = await this.client.getJoinedRooms();
roomData["joined_rooms"].forEach(async roomId => {
try {
await this.client.leave(roomId);
} catch (err) {
_logger.default.log('error', "ERROR LEAVING ROOM => " + err);
}
});
}
async sendBotSignal(roomId, signal, args) {
let content = {
signal: signal,
args: args
};
await this.client.sendStateEvent(roomId, 'm.bot.signal', content);
try {
await this.client.sendStateEvent(roomId, 'm.bot.signal', content);
} catch (err) {
_logger.default.log('error', "ERROR SENDING BOT SIGNAL => " + err);
}
}
async start() {
const localStorage = this.createLocalStorage();
this.localStorage = localStorage;
try {
const localStorage = this.createLocalStorage();
this.localStorage = localStorage;
const auth = {
user: this.config.BOT_USERNAME,
password: this.config.BOT_PASSWORD,
@@ -614,6 +665,7 @@ class OcrccBot {
if (state === 'PREPARED') {
await this.deleteOldDevices();
await this.leaveEmptyRooms();
await this.trackJoinedRooms();
await this.setMembershipListeners();
await this.setMessageListeners();

14
dist/bot.test.js vendored
View File

@@ -103,6 +103,8 @@ describe('OcrccBot', () => {
mockAppendFileSync.mockClear();
_matrixJsSdk.mockGetGroupUsers.mockClear();
_matrixJsSdk.mockSendStateEvent.mockClear();
});
test('constructor should inititialize class variables', () => {
const bot = new _bot.default(botConfig);
@@ -276,4 +278,16 @@ describe('OcrccBot', () => {
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
});
});
test('#sendBotSignal should send custom state event', () => {
const bot = new _bot.default(botConfig);
bot.start();
const test_room_id = 'test_room_id';
const signal = 'END_CHAT';
bot.sendBotSignal(test_room_id, signal);
(0, _waitForExpect.default)(() => {
expect(_matrixJsSdk.mockSendStateEvent).toHaveBeenCalledWith(test_room_id, 'm.bot.signal', {
signal
});
});
});
});

17
dist/index.js vendored
View File

@@ -19,7 +19,10 @@ const {
BOT_PASSWORD,
BOT_DISPLAY_NAME,
FACILITATOR_ROOM_ID,
CAPTURE_TRANSCRIPTS
CAPTURE_TRANSCRIPTS,
CHAT_NOT_AVAILABLE_MESSAGE,
MAX_WAIT_TIME,
MAX_INACTIVE
} = process.env;
const botConfig = {
ENCRYPTION_CONFIG,
@@ -32,7 +35,15 @@ const botConfig = {
BOT_PASSWORD,
BOT_DISPLAY_NAME,
FACILITATOR_ROOM_ID,
CAPTURE_TRANSCRIPTS
CAPTURE_TRANSCRIPTS,
CHAT_NOT_AVAILABLE_MESSAGE,
MAX_WAIT_TIME,
MAX_INACTIVE
};
const bot = new _bot.default(botConfig);
bot.start();
try {
bot.start();
} catch (err) {
console.log("AAAAAAAAAAAAA", err);
}

View File

@@ -1,6 +1,6 @@
{
"name": "private-safesupport-bot",
"version": "1.2.0",
"version": "2.0.2",
"description": "Chatbot to manage interactions on Safe Support Chat",
"main": "dist/index.js",
"scripts": {

View File

@@ -12,6 +12,7 @@ import logger from "./logger";
import encrypt from "./encrypt-attachment";
const BOT_SIGNAL_END_CHAT = 'END_CHAT'
const BOT_SIGNAL_CHAT_OFFLINE = 'CHAT_OFFLINE'
class OcrccBot {
@@ -32,21 +33,20 @@ class OcrccBot {
return new LocalStorage(localStoragePath);
}
sendTextMessage(roomId, msgText, showToUser = null) {
async sendTextMessage(roomId, msgText, showToUser = null) {
const content = {
msgtype: "m.text",
body: msgText,
showToUser: showToUser
};
this.sendMessage(roomId, content);
await this.sendMessage(roomId, content);
}
async sendNotice(roomId, message) {
logger.log("info", `SENDING *NOTICE*: ${message}`)
try {
await this.client.sendNotice(roomId, message)
logger.log("info", `SENT *NOTICE*: ${message}`)
} catch(err) {
switch (err["name"]) {
case "UnknownDeviceError":
@@ -109,10 +109,9 @@ class OcrccBot {
}
async inviteFacilitators(roomId) {
this.localStorage.setItem(`${roomId}-waiting`, 'true')
let invitations = []
try {
this.localStorage.setItem(`${roomId}-waiting`, 'true')
let invitations = []
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID)
const members = Object.keys(roomMembers["joined"]);
@@ -132,7 +131,7 @@ class OcrccBot {
this.localStorage.setItem(`${roomId}-invitations`, invitations)
} else {
logger.log('info', "NO FACILITATORS ONLINE")
this.sendNotice(roomId, "CHAT_OFFLINE")
this.sendBotSignal(roomId, BOT_SIGNAL_CHAT_OFFLINE)
}
} catch(err) {
@@ -143,9 +142,8 @@ class OcrccBot {
async uninviteFacilitators(roomId) {
this.localStorage.removeItem(`${roomId}-waiting`)
try {
this.localStorage.removeItem(`${roomId}-waiting`)
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID)
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId)
@@ -173,7 +171,7 @@ class OcrccBot {
this.sendTextMessage(
this.config.FACILITATOR_ROOM_ID,
`The Help Bot ran into an error: ${error}. Please verify that the chat service is working.`
`${this.config.BOT_DISPLAY_NAME} ran into an error: ${error}. Please verify that the chat service is working.`
);
}
@@ -216,7 +214,7 @@ class OcrccBot {
const filepath = this.localStorage.getItem(`${roomId}-transcript`)
if (!filepath) {
return logger.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}`);
return logger.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}. This message will not be added: ${content.body}`);
}
const message = `${sender} [${time}]: ${content.body}\n`;
@@ -235,7 +233,7 @@ class OcrccBot {
},
{
keyword: 'delete transcript',
function: (senderId, roomId) => { this.deleteTranscript(senderId, roomId) }
function: (senderId, roomId) => { this.deleteTranscript(senderId, roomId, true) } // delete transcript and send confirmation message
},
{
keyword: 'say',
@@ -280,7 +278,7 @@ class OcrccBot {
}
}
async leaveEmptyRooms(senderId) {
async leaveEmptyRooms() {
try {
const roomData = await this.client.getJoinedRooms()
const joinedRoomsIds = roomData["joined_rooms"]
@@ -288,15 +286,15 @@ class OcrccBot {
const room = this.client.getRoom(roomId)
if (room && room.getJoinedMemberCount() === 1) {
try {
logger.log('info', "LEAVING EMPTY ROOM => " + roomId)
await this.client.leave(roomId)
logger.log('info', `LEAVING EMPTY ROOM => ${roomId}`)
} catch(err) {
logger.log('error', "ERROR LEAVING EMPTY ROOM => " + err)
logger.log('error', `ERROR LEAVING ROOM ${roomId} => ${err}`)
}
}
})
} catch(err) {
logger.log("error", `ERROR GETTING JOINED ROOMS: ${err}`);
logger.log("error", `ERROR LEAVING EMPTY ROOMS: ${err}`);
}
}
@@ -307,7 +305,7 @@ class OcrccBot {
if (!transcriptFile) {
this.sendTextMessage(
roomId,
"There is no transcript for this chat.",
"Cannot send transcript, there is no transcript for this chat.",
senderId
);
}
@@ -370,13 +368,13 @@ class OcrccBot {
}
}
deleteTranscript(senderId, roomId) {
deleteTranscript(senderId, roomId, sendConfirmation=false) {
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`)
if (!transcriptFile) {
return this.sendTextMessage(
roomId,
"There is no transcript for this chat.",
"Cannot delete transcript, there is no transcript for this chat.",
senderId
);
}
@@ -392,13 +390,17 @@ class OcrccBot {
senderId
);
}
this.localStorage.removeItem(`${roomId}-transcript`)
if (sendConfirmation) {
this.sendTextMessage(
roomId,
`The transcript file has been deleted.`,
senderId
);
}
logger.log('info', "DELETED TRANSCRIPT FILE => " + transcriptFile)
this.sendTextMessage(
roomId,
`The transcript file has been deleted.`,
senderId
);
this.localStorage.removeItem(`${roomId}-transcript`)
});
}
@@ -535,7 +537,22 @@ class OcrccBot {
const roomMembers = await room.getJoinedMembers() // array
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID) // object
const isBotInRoom = roomMembers.find(member => member.userId === this.config.BOT_USERID)
const isBotInRoom = Boolean(roomMembers.find(member => member.userId === this.config.BOT_USERID))
// leave if there is nobody in the room
try {
const memberCount = roomMembers.length
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.localStorage.removeItem(`${member.roomId}-waiting`)
return await this.client.leave(member.roomId)
}
} catch(err) {
return logger.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
}
// notify room if the facilitator has left
try {
@@ -545,25 +562,17 @@ class OcrccBot {
member.roomId,
`${member.name} has left the chat.`
);
// send notification to Support Chat Notifications room
const currentDate = new Date()
const chatTime = currentDate.toLocaleTimeString()
const roomId = member.roomId.split(':')[0]
const notification = `${member.name} left the chat at ${chatTime} (room ID: ${roomId})`
await this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification);
}
} catch(err) {
logger.log("error", `ERROR NOTIFYING THAT FACLITATOR HAS LEFT THE ROOM ==> ${err}`);
}
// leave if there is nobody in the room
try {
const memberCount = roomMembers.length
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`)
return this.client.leave(member.roomId)
}
} catch(err) {
logger.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
}
// send signal to close the chat if there are no facilitators in the room
try {
const facilitators = facilitatorRoomMembers['joined']
@@ -576,6 +585,7 @@ class OcrccBot {
})
if (!facilitatorInRoom) {
logger.log("info", `NO FACILITATORS LEFT, SENDING SIGNAL TO END CHAT`);
this.sendBotSignal(member.roomId, BOT_SIGNAL_END_CHAT)
}
@@ -587,9 +597,14 @@ class OcrccBot {
}
setTimeoutforFacilitator(roomId) {
setTimeout(() => {
setTimeout(async() => {
const stillWaiting = this.localStorage.getItem(`${roomId}-waiting`)
if (stillWaiting) {
logger.log("info", `FACILITATOR DID NOT JOIN CHAT WITHIN TIME LIMIT, SENDING SIGNAL TO END CHAT`);
await this.sendTextMessage(
roomId,
this.config.CHAT_NOT_AVAILABLE_MESSAGE
);
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
}
}, this.config.MAX_WAIT_TIME)
@@ -602,8 +617,9 @@ class OcrccBot {
clearTimeout(oldTimeout);
}
const newTimeout = setTimeout(() => {
this.sendTextMessage(
const newTimeout = setTimeout(async() => {
logger.log("info", `CHAT IS INACTIVE, SENDING SIGNAL TO END CHAT`);
await this.sendTextMessage(
roomId,
`This chat has been closed due to inactivity.`
);
@@ -631,18 +647,6 @@ class OcrccBot {
});
}
async leaveOldRooms() {
const roomData = await this.client.getJoinedRooms()
roomData["joined_rooms"].forEach(async roomId => {
try {
await this.client.leave(roomId)
} catch(err) {
logger.log('error', "ERROR LEAVING ROOM => " + err)
}
})
}
async sendBotSignal (roomId, signal, args) {
let content = {
signal: signal,
@@ -656,10 +660,10 @@ class OcrccBot {
}
async start() {
const localStorage = this.createLocalStorage();
this.localStorage = localStorage
try {
const localStorage = this.createLocalStorage();
this.localStorage = localStorage
const auth = {
user: this.config.BOT_USERNAME,
password: this.config.BOT_PASSWORD,
@@ -684,6 +688,7 @@ class OcrccBot {
logger.log("info", `SYNC STATUS: ${state}`)
if (state === 'PREPARED') {
await this.deleteOldDevices()
await this.leaveEmptyRooms()
await this.trackJoinedRooms()
await this.setMembershipListeners();
await this.setMessageListeners();

View File

@@ -39,4 +39,8 @@ const botConfig = {
import OcrccBot from './bot'
const bot = new OcrccBot(botConfig);
bot.start();
try {
bot.start();
} catch(err) {
console.log("AAAAAAAAAAAAA", err)
}