Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
687dfa84e9 | ||
|
|
b7da515969 | ||
|
|
e2c291c040 | ||
|
|
87f2c5290f | ||
|
|
4fdddc8c92 | ||
|
|
d53a5c5e26 | ||
|
|
9772b3b1fd | ||
|
|
84fe91adbb | ||
|
|
b6cd85eab0 | ||
|
|
209b3aaa45 | ||
|
|
4912ce6f61 | ||
|
|
013ffa318f | ||
|
|
ac2f953b90 | ||
|
|
a25c71a04a | ||
|
|
836d4751ad | ||
|
|
2983a14038 | ||
|
|
6e71ba4b5b | ||
|
|
5dc6aa5660 | ||
|
|
6d4b6b1609 | ||
|
|
1e3b63fe5b |
@@ -1,5 +1,10 @@
|
|||||||
FROM node:10-alpine
|
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
|
RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app
|
||||||
|
|
||||||
WORKDIR /home/node/app
|
WORKDIR /home/node/app
|
||||||
|
|||||||
@@ -157,6 +157,10 @@ export const mockGetGroupUsers = jest.fn(() => {
|
|||||||
|
|
||||||
export const mockGetUser = jest.fn().mockReturnValue({ presence: 'online'});
|
export const mockGetUser = jest.fn().mockReturnValue({ presence: 'online'});
|
||||||
|
|
||||||
|
export const mockSendStateEvent = jest.fn(() => {
|
||||||
|
return Promise.resolve();
|
||||||
|
});
|
||||||
|
|
||||||
export const mockClient = {
|
export const mockClient = {
|
||||||
registerRequest: mockRegisterRequest,
|
registerRequest: mockRegisterRequest,
|
||||||
initCrypto: mockInitCrypto,
|
initCrypto: mockInitCrypto,
|
||||||
@@ -186,6 +190,7 @@ export const mockClient = {
|
|||||||
getJoinedRoomMembers: mockGetJoinedRoomMembers,
|
getJoinedRoomMembers: mockGetJoinedRoomMembers,
|
||||||
getUser: mockGetUser,
|
getUser: mockGetUser,
|
||||||
getGroupUsers: mockGetGroupUsers,
|
getGroupUsers: mockGetGroupUsers,
|
||||||
|
sendStateEvent: mockSendStateEvent,
|
||||||
}
|
}
|
||||||
|
|
||||||
export const WebStorageSessionStore = jest.fn()
|
export const WebStorageSessionStore = jest.fn()
|
||||||
|
|||||||
220
dist/bot.js
vendored
220
dist/bot.js
vendored
@@ -26,12 +26,15 @@ var _logger = _interopRequireDefault(require("./logger"));
|
|||||||
var _encryptAttachment = _interopRequireDefault(require("./encrypt-attachment"));
|
var _encryptAttachment = _interopRequireDefault(require("./encrypt-attachment"));
|
||||||
|
|
||||||
global.Olm = require("olm");
|
global.Olm = require("olm");
|
||||||
|
const BOT_SIGNAL_END_CHAT = 'END_CHAT';
|
||||||
|
const BOT_SIGNAL_CHAT_OFFLINE = 'CHAT_OFFLINE';
|
||||||
|
|
||||||
class OcrccBot {
|
class OcrccBot {
|
||||||
constructor(botConfig) {
|
constructor(botConfig) {
|
||||||
this.config = botConfig;
|
this.config = botConfig;
|
||||||
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
|
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
|
||||||
this.joinedRooms = [];
|
this.joinedRooms = [];
|
||||||
|
this.inactivityTimers = {};
|
||||||
}
|
}
|
||||||
|
|
||||||
createLocalStorage() {
|
createLocalStorage() {
|
||||||
@@ -46,20 +49,20 @@ class OcrccBot {
|
|||||||
return new _nodeLocalstorage.LocalStorage(localStoragePath);
|
return new _nodeLocalstorage.LocalStorage(localStoragePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
sendTextMessage(roomId, msgText, showToUser = null) {
|
async sendTextMessage(roomId, msgText, showToUser = null) {
|
||||||
const content = {
|
const content = {
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: msgText,
|
body: msgText,
|
||||||
showToUser: showToUser
|
showToUser: showToUser
|
||||||
};
|
};
|
||||||
this.sendMessage(roomId, content);
|
await this.sendMessage(roomId, content);
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendNotice(roomId, message) {
|
async sendNotice(roomId, message) {
|
||||||
_logger.default.log("info", `SENDING *NOTICE*: ${message}`);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await this.client.sendNotice(roomId, message);
|
await this.client.sendNotice(roomId, message);
|
||||||
|
|
||||||
|
_logger.default.log("info", `SENT *NOTICE*: ${message}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
switch (err["name"]) {
|
switch (err["name"]) {
|
||||||
case "UnknownDeviceError":
|
case "UnknownDeviceError":
|
||||||
@@ -128,10 +131,9 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async inviteFacilitators(roomId) {
|
async inviteFacilitators(roomId) {
|
||||||
|
try {
|
||||||
this.localStorage.setItem(`${roomId}-waiting`, 'true');
|
this.localStorage.setItem(`${roomId}-waiting`, 'true');
|
||||||
let invitations = [];
|
let invitations = [];
|
||||||
|
|
||||||
try {
|
|
||||||
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
|
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
|
||||||
const members = Object.keys(roomMembers["joined"]);
|
const members = Object.keys(roomMembers["joined"]);
|
||||||
members.forEach(memberId => {
|
members.forEach(memberId => {
|
||||||
@@ -148,7 +150,7 @@ class OcrccBot {
|
|||||||
} else {
|
} else {
|
||||||
_logger.default.log('info', "NO FACILITATORS ONLINE");
|
_logger.default.log('info', "NO FACILITATORS ONLINE");
|
||||||
|
|
||||||
this.sendNotice(roomId, "CHAT_OFFLINE");
|
this.sendBotSignal(roomId, BOT_SIGNAL_CHAT_OFFLINE);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.handleBotCrash(roomId, err);
|
this.handleBotCrash(roomId, err);
|
||||||
@@ -158,9 +160,8 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async uninviteFacilitators(roomId) {
|
async uninviteFacilitators(roomId) {
|
||||||
this.localStorage.removeItem(`${roomId}-waiting`);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
this.localStorage.removeItem(`${roomId}-waiting`);
|
||||||
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
|
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
|
||||||
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId);
|
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId);
|
||||||
const roomMembersIds = Object.keys(supportRoomMembers["joined"]);
|
const roomMembersIds = Object.keys(supportRoomMembers["joined"]);
|
||||||
@@ -183,14 +184,23 @@ class OcrccBot {
|
|||||||
this.sendTextMessage(roomId, this.config.BOT_ERROR_MESSAGE);
|
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) {
|
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) {
|
if (!content) {
|
||||||
return;
|
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
|
} // bot commands
|
||||||
|
|
||||||
|
|
||||||
@@ -216,7 +226,7 @@ class OcrccBot {
|
|||||||
const filepath = this.localStorage.getItem(`${roomId}-transcript`);
|
const filepath = this.localStorage.getItem(`${roomId}-transcript`);
|
||||||
|
|
||||||
if (!filepath) {
|
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`;
|
const message = `${sender} [${time}]: ${content.body}\n`;
|
||||||
@@ -227,41 +237,50 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handleBotCommand(event) {
|
handleBotCommand(event) {
|
||||||
|
const botCommands = [{
|
||||||
|
keyword: 'transcript',
|
||||||
|
function: (senderId, roomId) => {
|
||||||
|
this.sendTranscript(senderId, roomId);
|
||||||
|
}
|
||||||
|
}, {
|
||||||
|
keyword: 'delete transcript',
|
||||||
|
function: (senderId, roomId) => {
|
||||||
|
this.deleteTranscript(senderId, roomId, true);
|
||||||
|
} // delete transcript and send confirmation message
|
||||||
|
|
||||||
|
}, {
|
||||||
|
keyword: 'say',
|
||||||
|
function: (senderId, roomId, message) => {
|
||||||
|
this.sendTextMessage(roomId, message, senderId);
|
||||||
|
}
|
||||||
|
}, {
|
||||||
|
keyword: 'hi',
|
||||||
|
function: (senderId, roomId) => {
|
||||||
|
const responses = ["Hi!", "Hello", "Hey :)", "Hi there", "Bleep bloop"];
|
||||||
|
const message = responses[Math.floor(Math.random() * responses.length)];
|
||||||
|
this.sendTextMessage(roomId, message, senderId);
|
||||||
|
}
|
||||||
|
}];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const senderId = event.getSender();
|
const senderId = event.getSender();
|
||||||
const roomId = event.getRoomId();
|
const roomId = event.getRoomId();
|
||||||
const content = event.getContent();
|
const content = event.getContent();
|
||||||
const command = content.body.substring("!bot".length).trim();
|
const commandText = content.body.substring("!bot".length).trim();
|
||||||
|
const command = botCommands.find(c => commandText.startsWith(c.keyword));
|
||||||
|
|
||||||
switch (command) {
|
if (!command) {
|
||||||
case "transcript":
|
|
||||||
this.sendTranscript(senderId, roomId);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "transcript please":
|
|
||||||
this.sendTranscript(senderId, roomId);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "delete transcript":
|
|
||||||
this.deleteTranscript(senderId, roomId);
|
|
||||||
break;
|
|
||||||
|
|
||||||
case "hi":
|
|
||||||
const responses = ["Hi!", "Hello", "Hey :)", "Hi there", "Bleep bloop"];
|
|
||||||
const message = responses[Math.floor(Math.random() * responses.length)];
|
|
||||||
this.sendTextMessage(roomId, message, senderId);
|
|
||||||
break;
|
|
||||||
|
|
||||||
default:
|
|
||||||
this.sendTextMessage(roomId, `Sorry, I don't know that command. I'm not a very smart bot.`, senderId);
|
this.sendTextMessage(roomId, `Sorry, I don't know that command. I'm not a very smart bot.`, senderId);
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const args = commandText.substring(command.keyword.length).trim();
|
||||||
|
command.function(senderId, roomId, args);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
_logger.default.log("error", `ERROR EXECUTING BOT COMMAND: ${err}`);
|
_logger.default.log("error", `ERROR EXECUTING BOT COMMAND: ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async leaveEmptyRooms(senderId) {
|
async leaveEmptyRooms() {
|
||||||
try {
|
try {
|
||||||
const roomData = await this.client.getJoinedRooms();
|
const roomData = await this.client.getJoinedRooms();
|
||||||
const joinedRoomsIds = roomData["joined_rooms"];
|
const joinedRoomsIds = roomData["joined_rooms"];
|
||||||
@@ -270,16 +289,16 @@ class OcrccBot {
|
|||||||
|
|
||||||
if (room && room.getJoinedMemberCount() === 1) {
|
if (room && room.getJoinedMemberCount() === 1) {
|
||||||
try {
|
try {
|
||||||
_logger.default.log('info', "LEAVING EMPTY ROOM => " + roomId);
|
|
||||||
|
|
||||||
await this.client.leave(roomId);
|
await this.client.leave(roomId);
|
||||||
|
|
||||||
|
_logger.default.log('info', `LEAVING EMPTY ROOM => ${roomId}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
_logger.default.log('error', "ERROR LEAVING EMPTY ROOM => " + err);
|
_logger.default.log('error', `ERROR LEAVING ROOM ${roomId} => ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
_logger.default.log("error", `ERROR GETTING JOINED ROOMS: ${err}`);
|
_logger.default.log("error", `ERROR LEAVING EMPTY ROOMS: ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,7 +307,7 @@ class OcrccBot {
|
|||||||
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
|
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
|
||||||
|
|
||||||
if (!transcriptFile) {
|
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)) {
|
if (this.client.isRoomEncrypted(roomId)) {
|
||||||
@@ -347,11 +366,11 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteTranscript(senderId, roomId) {
|
deleteTranscript(senderId, roomId, sendConfirmation = false) {
|
||||||
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
|
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
|
||||||
|
|
||||||
if (!transcriptFile) {
|
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 => {
|
fs.unlink(transcriptFile, err => {
|
||||||
@@ -363,11 +382,13 @@ class OcrccBot {
|
|||||||
return this.sendTextMessage(roomId, `There was an error deleting the transcript: ${err}`, senderId);
|
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);
|
_logger.default.log('info', "DELETED TRANSCRIPT FILE => " + transcriptFile);
|
||||||
|
|
||||||
this.sendTextMessage(roomId, `The transcript file has been deleted.`, senderId);
|
this.localStorage.removeItem(`${roomId}-transcript`);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -418,13 +439,14 @@ class OcrccBot {
|
|||||||
|
|
||||||
_logger.default.log("info", "AUTO JOINED ROOM => " + room.roomId);
|
_logger.default.log("info", "AUTO JOINED ROOM => " + room.roomId);
|
||||||
|
|
||||||
const currentDate = new Date();
|
const inviteDate = event.getDate();
|
||||||
const chatDate = currentDate.toLocaleDateString();
|
const chatDate = inviteDate.toLocaleDateString();
|
||||||
const chatTime = currentDate.toLocaleTimeString();
|
const chatTime = inviteDate.toLocaleTimeString();
|
||||||
const roomId = room.roomId.split(':')[0];
|
const roomId = room.roomId.split(':')[0];
|
||||||
const notification = `Incoming support chat at ${chatTime} (room ID: ${roomId})`;
|
const notification = `Incoming support chat at ${chatTime} (room ID: ${roomId})`;
|
||||||
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification);
|
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification);
|
||||||
this.inviteFacilitators(room.roomId);
|
this.inviteFacilitators(room.roomId);
|
||||||
|
this.setTimeoutforFacilitator(room.roomId);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
_logger.default.log("error", "ERROR JOINING ROOM => " + err);
|
_logger.default.log("error", "ERROR JOINING ROOM => " + err);
|
||||||
@@ -432,6 +454,7 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (member.membership === "join" && member.userId !== this.config.BOT_USERID && this.localStorage.getItem(`${member.roomId}-waiting`)) {
|
if (member.membership === "join" && member.userId !== this.config.BOT_USERID && this.localStorage.getItem(`${member.roomId}-waiting`)) {
|
||||||
|
try {
|
||||||
// make sure it's a facilitator joining
|
// make sure it's a facilitator joining
|
||||||
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
|
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
|
||||||
const members = Object.keys(roomMembers["joined"]);
|
const members = Object.keys(roomMembers["joined"]);
|
||||||
@@ -481,38 +504,105 @@ class OcrccBot {
|
|||||||
this.localStorage.setItem(`${member.roomId}-transcript`, filepath);
|
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) {
|
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);
|
const room = this.client.getRoom(member.roomId);
|
||||||
if (!room) return; // leave if there is nobody in the room
|
if (!room) return;
|
||||||
|
const roomMembers = await room.getJoinedMembers(); // array
|
||||||
|
|
||||||
const memberCount = room.getJoinedMemberCount();
|
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 = roomMembers.length;
|
||||||
|
|
||||||
if (memberCount === 1 && isBotInRoom) {
|
if (memberCount === 1 && isBotInRoom) {
|
||||||
// just the bot left
|
// 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.deleteTranscript(member.userId, member.roomId);
|
||||||
this.localStorage.removeItem(`${member.roomId}-facilitator`);
|
this.localStorage.removeItem(`${member.roomId}-facilitator`);
|
||||||
this.localStorage.removeItem(`${member.roomId}-transcript`);
|
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) {
|
||||||
|
return _logger.default.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
|
||||||
} // notify room if the facilitator has left
|
} // notify room if the facilitator has left
|
||||||
|
|
||||||
|
|
||||||
|
try {
|
||||||
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`);
|
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`);
|
||||||
|
|
||||||
if (isBotInRoom && member.userId === facilitatorId) {
|
if (isBotInRoom && member.userId === facilitatorId) {
|
||||||
this.sendTextMessage(member.roomId, `${member.name} has left the chat.`);
|
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 facilitators = facilitatorRoomMembers['joined'];
|
||||||
|
let facilitatorInRoom = false;
|
||||||
|
roomMembers.forEach(member => {
|
||||||
|
if (member.userId !== this.config.BOT_USERID && Boolean(facilitators[member.userId])) {
|
||||||
|
facilitatorInRoom = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!facilitatorInRoom) {
|
||||||
|
_logger.default.log("info", `NO FACILITATORS LEFT, SENDING SIGNAL TO END CHAT`);
|
||||||
|
|
||||||
|
this.sendBotSignal(member.roomId, BOT_SIGNAL_END_CHAT);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
_logger.default.log("error", `ERROR SENDING BOT SIGNAL ==> ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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() {
|
async setMessageListeners() {
|
||||||
// encrypted messages
|
// encrypted messages
|
||||||
this.client.on("Event.decrypted", (event, err) => {
|
this.client.on("Event.decrypted", (event, err) => {
|
||||||
@@ -532,22 +622,23 @@ class OcrccBot {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async leaveOldRooms() {
|
async sendBotSignal(roomId, signal, args) {
|
||||||
const roomData = await this.client.getJoinedRooms();
|
let content = {
|
||||||
roomData["joined_rooms"].forEach(async roomId => {
|
signal: signal,
|
||||||
|
args: args
|
||||||
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await this.client.leave(roomId);
|
await this.client.sendStateEvent(roomId, 'm.bot.signal', content);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
_logger.default.log('error', "ERROR LEAVING ROOM => " + err);
|
_logger.default.log('error', "ERROR SENDING BOT SIGNAL => " + err);
|
||||||
}
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async start() {
|
async start() {
|
||||||
|
try {
|
||||||
const localStorage = this.createLocalStorage();
|
const localStorage = this.createLocalStorage();
|
||||||
this.localStorage = localStorage;
|
this.localStorage = localStorage;
|
||||||
|
|
||||||
try {
|
|
||||||
const auth = {
|
const auth = {
|
||||||
user: this.config.BOT_USERNAME,
|
user: this.config.BOT_USERNAME,
|
||||||
password: this.config.BOT_PASSWORD,
|
password: this.config.BOT_PASSWORD,
|
||||||
@@ -574,6 +665,7 @@ class OcrccBot {
|
|||||||
|
|
||||||
if (state === 'PREPARED') {
|
if (state === 'PREPARED') {
|
||||||
await this.deleteOldDevices();
|
await this.deleteOldDevices();
|
||||||
|
await this.leaveEmptyRooms();
|
||||||
await this.trackJoinedRooms();
|
await this.trackJoinedRooms();
|
||||||
await this.setMembershipListeners();
|
await this.setMembershipListeners();
|
||||||
await this.setMessageListeners();
|
await this.setMessageListeners();
|
||||||
|
|||||||
14
dist/bot.test.js
vendored
14
dist/bot.test.js
vendored
@@ -103,6 +103,8 @@ describe('OcrccBot', () => {
|
|||||||
mockAppendFileSync.mockClear();
|
mockAppendFileSync.mockClear();
|
||||||
|
|
||||||
_matrixJsSdk.mockGetGroupUsers.mockClear();
|
_matrixJsSdk.mockGetGroupUsers.mockClear();
|
||||||
|
|
||||||
|
_matrixJsSdk.mockSendStateEvent.mockClear();
|
||||||
});
|
});
|
||||||
test('constructor should inititialize class variables', () => {
|
test('constructor should inititialize class variables', () => {
|
||||||
const bot = new _bot.default(botConfig);
|
const bot = new _bot.default(botConfig);
|
||||||
@@ -276,4 +278,16 @@ describe('OcrccBot', () => {
|
|||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
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
17
dist/index.js
vendored
@@ -19,7 +19,10 @@ const {
|
|||||||
BOT_PASSWORD,
|
BOT_PASSWORD,
|
||||||
BOT_DISPLAY_NAME,
|
BOT_DISPLAY_NAME,
|
||||||
FACILITATOR_ROOM_ID,
|
FACILITATOR_ROOM_ID,
|
||||||
CAPTURE_TRANSCRIPTS
|
CAPTURE_TRANSCRIPTS,
|
||||||
|
CHAT_NOT_AVAILABLE_MESSAGE,
|
||||||
|
MAX_WAIT_TIME,
|
||||||
|
MAX_INACTIVE
|
||||||
} = process.env;
|
} = process.env;
|
||||||
const botConfig = {
|
const botConfig = {
|
||||||
ENCRYPTION_CONFIG,
|
ENCRYPTION_CONFIG,
|
||||||
@@ -32,7 +35,15 @@ const botConfig = {
|
|||||||
BOT_PASSWORD,
|
BOT_PASSWORD,
|
||||||
BOT_DISPLAY_NAME,
|
BOT_DISPLAY_NAME,
|
||||||
FACILITATOR_ROOM_ID,
|
FACILITATOR_ROOM_ID,
|
||||||
CAPTURE_TRANSCRIPTS
|
CAPTURE_TRANSCRIPTS,
|
||||||
|
CHAT_NOT_AVAILABLE_MESSAGE,
|
||||||
|
MAX_WAIT_TIME,
|
||||||
|
MAX_INACTIVE
|
||||||
};
|
};
|
||||||
const bot = new _bot.default(botConfig);
|
const bot = new _bot.default(botConfig);
|
||||||
bot.start();
|
|
||||||
|
try {
|
||||||
|
bot.start();
|
||||||
|
} catch (err) {
|
||||||
|
console.log("AAAAAAAAAAAAA", err);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "private-safesupport-bot",
|
"name": "private-safesupport-bot",
|
||||||
"version": "1.2.0",
|
"version": "2.0.2",
|
||||||
"description": "Chatbot to manage interactions on Safe Support Chat",
|
"description": "Chatbot to manage interactions on Safe Support Chat",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
225
src/bot.js
225
src/bot.js
@@ -11,12 +11,16 @@ import * as matrix from "matrix-js-sdk";
|
|||||||
import logger from "./logger";
|
import logger from "./logger";
|
||||||
import encrypt from "./encrypt-attachment";
|
import encrypt from "./encrypt-attachment";
|
||||||
|
|
||||||
|
const BOT_SIGNAL_END_CHAT = 'END_CHAT'
|
||||||
|
const BOT_SIGNAL_CHAT_OFFLINE = 'CHAT_OFFLINE'
|
||||||
|
|
||||||
|
|
||||||
class OcrccBot {
|
class OcrccBot {
|
||||||
constructor(botConfig) {
|
constructor(botConfig) {
|
||||||
this.config = botConfig
|
this.config = botConfig
|
||||||
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
|
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
|
||||||
this.joinedRooms = [];
|
this.joinedRooms = [];
|
||||||
|
this.inactivityTimers = {};
|
||||||
}
|
}
|
||||||
|
|
||||||
createLocalStorage() {
|
createLocalStorage() {
|
||||||
@@ -29,21 +33,20 @@ class OcrccBot {
|
|||||||
return new LocalStorage(localStoragePath);
|
return new LocalStorage(localStoragePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
sendTextMessage(roomId, msgText, showToUser = null) {
|
async sendTextMessage(roomId, msgText, showToUser = null) {
|
||||||
const content = {
|
const content = {
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: msgText,
|
body: msgText,
|
||||||
showToUser: showToUser
|
showToUser: showToUser
|
||||||
};
|
};
|
||||||
|
|
||||||
this.sendMessage(roomId, content);
|
await this.sendMessage(roomId, content);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async sendNotice(roomId, message) {
|
async sendNotice(roomId, message) {
|
||||||
logger.log("info", `SENDING *NOTICE*: ${message}`)
|
|
||||||
try {
|
try {
|
||||||
await this.client.sendNotice(roomId, message)
|
await this.client.sendNotice(roomId, message)
|
||||||
|
logger.log("info", `SENT *NOTICE*: ${message}`)
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
switch (err["name"]) {
|
switch (err["name"]) {
|
||||||
case "UnknownDeviceError":
|
case "UnknownDeviceError":
|
||||||
@@ -106,10 +109,9 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async inviteFacilitators(roomId) {
|
async inviteFacilitators(roomId) {
|
||||||
|
try {
|
||||||
this.localStorage.setItem(`${roomId}-waiting`, 'true')
|
this.localStorage.setItem(`${roomId}-waiting`, 'true')
|
||||||
let invitations = []
|
let invitations = []
|
||||||
|
|
||||||
try {
|
|
||||||
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID)
|
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID)
|
||||||
const members = Object.keys(roomMembers["joined"]);
|
const members = Object.keys(roomMembers["joined"]);
|
||||||
|
|
||||||
@@ -129,7 +131,7 @@ class OcrccBot {
|
|||||||
this.localStorage.setItem(`${roomId}-invitations`, invitations)
|
this.localStorage.setItem(`${roomId}-invitations`, invitations)
|
||||||
} else {
|
} else {
|
||||||
logger.log('info', "NO FACILITATORS ONLINE")
|
logger.log('info', "NO FACILITATORS ONLINE")
|
||||||
this.sendNotice(roomId, "CHAT_OFFLINE")
|
this.sendBotSignal(roomId, BOT_SIGNAL_CHAT_OFFLINE)
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
@@ -140,9 +142,8 @@ class OcrccBot {
|
|||||||
|
|
||||||
|
|
||||||
async uninviteFacilitators(roomId) {
|
async uninviteFacilitators(roomId) {
|
||||||
this.localStorage.removeItem(`${roomId}-waiting`)
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
this.localStorage.removeItem(`${roomId}-waiting`)
|
||||||
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID)
|
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID)
|
||||||
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId)
|
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId)
|
||||||
|
|
||||||
@@ -170,18 +171,26 @@ class OcrccBot {
|
|||||||
|
|
||||||
this.sendTextMessage(
|
this.sendTextMessage(
|
||||||
this.config.FACILITATOR_ROOM_ID,
|
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.`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
handleMessageEvent(event) {
|
handleMessageEvent(event) {
|
||||||
const content = event.getContent();
|
const content = event.getContent();
|
||||||
|
const sender = event.getSender()
|
||||||
|
const roomId = event.getRoomId();
|
||||||
|
|
||||||
// do nothing if there's no content
|
// do nothing if there's no content
|
||||||
if (!content) {
|
if (!content) {
|
||||||
return;
|
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
|
// bot commands
|
||||||
if (content.body.startsWith("!bot")) {
|
if (content.body.startsWith("!bot")) {
|
||||||
return this.handleBotCommand(event);
|
return this.handleBotCommand(event);
|
||||||
@@ -205,7 +214,7 @@ class OcrccBot {
|
|||||||
const filepath = this.localStorage.getItem(`${roomId}-transcript`)
|
const filepath = this.localStorage.getItem(`${roomId}-transcript`)
|
||||||
|
|
||||||
if (!filepath) {
|
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`;
|
const message = `${sender} [${time}]: ${content.body}\n`;
|
||||||
@@ -217,23 +226,24 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
handleBotCommand(event) {
|
handleBotCommand(event) {
|
||||||
try {
|
const botCommands = [
|
||||||
const senderId = event.getSender();
|
{
|
||||||
const roomId = event.getRoomId();
|
keyword: 'transcript',
|
||||||
const content = event.getContent();
|
function: (senderId, roomId) => { this.sendTranscript(senderId, roomId) }
|
||||||
const command = content.body.substring("!bot".length).trim();
|
},
|
||||||
|
{
|
||||||
switch (command) {
|
keyword: 'delete transcript',
|
||||||
case "transcript":
|
function: (senderId, roomId) => { this.deleteTranscript(senderId, roomId, true) } // delete transcript and send confirmation message
|
||||||
this.sendTranscript(senderId, roomId);
|
},
|
||||||
break;
|
{
|
||||||
case "transcript please":
|
keyword: 'say',
|
||||||
this.sendTranscript(senderId, roomId);
|
function: (senderId, roomId, message) => {
|
||||||
break;
|
this.sendTextMessage(roomId, message, senderId);
|
||||||
case "delete transcript":
|
}
|
||||||
this.deleteTranscript(senderId, roomId);
|
},
|
||||||
break;
|
{
|
||||||
case "hi":
|
keyword: 'hi',
|
||||||
|
function: (senderId, roomId) => {
|
||||||
const responses = [
|
const responses = [
|
||||||
"Hi!",
|
"Hi!",
|
||||||
"Hello",
|
"Hello",
|
||||||
@@ -241,24 +251,34 @@ class OcrccBot {
|
|||||||
"Hi there",
|
"Hi there",
|
||||||
"Bleep bloop"
|
"Bleep bloop"
|
||||||
];
|
];
|
||||||
const message =
|
const message = responses[Math.floor(Math.random() * responses.length)];
|
||||||
responses[Math.floor(Math.random() * responses.length)];
|
|
||||||
this.sendTextMessage(roomId, message, senderId);
|
this.sendTextMessage(roomId, message, senderId);
|
||||||
break;
|
}
|
||||||
default:
|
}
|
||||||
|
]
|
||||||
|
try {
|
||||||
|
const senderId = event.getSender();
|
||||||
|
const roomId = event.getRoomId();
|
||||||
|
const content = event.getContent();
|
||||||
|
const commandText = content.body.substring("!bot".length).trim();
|
||||||
|
const command = botCommands.find(c => commandText.startsWith(c.keyword))
|
||||||
|
|
||||||
|
if (!command) {
|
||||||
this.sendTextMessage(
|
this.sendTextMessage(
|
||||||
roomId,
|
roomId,
|
||||||
`Sorry, I don't know that command. I'm not a very smart bot.`,
|
`Sorry, I don't know that command. I'm not a very smart bot.`,
|
||||||
senderId
|
senderId
|
||||||
);
|
);
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const args = commandText.substring(command.keyword.length).trim()
|
||||||
|
command.function(senderId, roomId, args)
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.log("error", `ERROR EXECUTING BOT COMMAND: ${err}`);
|
logger.log("error", `ERROR EXECUTING BOT COMMAND: ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async leaveEmptyRooms(senderId) {
|
async leaveEmptyRooms() {
|
||||||
try {
|
try {
|
||||||
const roomData = await this.client.getJoinedRooms()
|
const roomData = await this.client.getJoinedRooms()
|
||||||
const joinedRoomsIds = roomData["joined_rooms"]
|
const joinedRoomsIds = roomData["joined_rooms"]
|
||||||
@@ -266,15 +286,15 @@ class OcrccBot {
|
|||||||
const room = this.client.getRoom(roomId)
|
const room = this.client.getRoom(roomId)
|
||||||
if (room && room.getJoinedMemberCount() === 1) {
|
if (room && room.getJoinedMemberCount() === 1) {
|
||||||
try {
|
try {
|
||||||
logger.log('info', "LEAVING EMPTY ROOM => " + roomId)
|
|
||||||
await this.client.leave(roomId)
|
await this.client.leave(roomId)
|
||||||
|
logger.log('info', `LEAVING EMPTY ROOM => ${roomId}`)
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
logger.log('error', "ERROR LEAVING EMPTY ROOM => " + err)
|
logger.log('error', `ERROR LEAVING ROOM ${roomId} => ${err}`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
logger.log("error", `ERROR GETTING JOINED ROOMS: ${err}`);
|
logger.log("error", `ERROR LEAVING EMPTY ROOMS: ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -285,7 +305,7 @@ class OcrccBot {
|
|||||||
if (!transcriptFile) {
|
if (!transcriptFile) {
|
||||||
this.sendTextMessage(
|
this.sendTextMessage(
|
||||||
roomId,
|
roomId,
|
||||||
"There is no transcript for this chat.",
|
"Cannot send transcript, there is no transcript for this chat.",
|
||||||
senderId
|
senderId
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -348,13 +368,13 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteTranscript(senderId, roomId) {
|
deleteTranscript(senderId, roomId, sendConfirmation=false) {
|
||||||
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`)
|
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`)
|
||||||
|
|
||||||
if (!transcriptFile) {
|
if (!transcriptFile) {
|
||||||
return this.sendTextMessage(
|
return this.sendTextMessage(
|
||||||
roomId,
|
roomId,
|
||||||
"There is no transcript for this chat.",
|
"Cannot delete transcript, there is no transcript for this chat.",
|
||||||
senderId
|
senderId
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -370,13 +390,17 @@ class OcrccBot {
|
|||||||
senderId
|
senderId
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
this.localStorage.removeItem(`${roomId}-transcript`)
|
|
||||||
logger.log('info', "DELETED TRANSCRIPT FILE => " + transcriptFile)
|
if (sendConfirmation) {
|
||||||
this.sendTextMessage(
|
this.sendTextMessage(
|
||||||
roomId,
|
roomId,
|
||||||
`The transcript file has been deleted.`,
|
`The transcript file has been deleted.`,
|
||||||
senderId
|
senderId
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.log('info', "DELETED TRANSCRIPT FILE => " + transcriptFile)
|
||||||
|
this.localStorage.removeItem(`${roomId}-transcript`)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -423,13 +447,14 @@ class OcrccBot {
|
|||||||
if (!joinedRooms.includes(member.roomId)) {
|
if (!joinedRooms.includes(member.roomId)) {
|
||||||
const room = await this.client.joinRoom(member.roomId)
|
const room = await this.client.joinRoom(member.roomId)
|
||||||
logger.log("info", "AUTO JOINED ROOM => " + room.roomId)
|
logger.log("info", "AUTO JOINED ROOM => " + room.roomId)
|
||||||
const currentDate = new Date()
|
const inviteDate = event.getDate()
|
||||||
const chatDate = currentDate.toLocaleDateString()
|
const chatDate = inviteDate.toLocaleDateString()
|
||||||
const chatTime = currentDate.toLocaleTimeString()
|
const chatTime = inviteDate.toLocaleTimeString()
|
||||||
const roomId = room.roomId.split(':')[0]
|
const roomId = room.roomId.split(':')[0]
|
||||||
const notification = `Incoming support chat at ${chatTime} (room ID: ${roomId})`
|
const notification = `Incoming support chat at ${chatTime} (room ID: ${roomId})`
|
||||||
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification);
|
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification);
|
||||||
this.inviteFacilitators(room.roomId)
|
this.inviteFacilitators(room.roomId)
|
||||||
|
this.setTimeoutforFacilitator(room.roomId)
|
||||||
}
|
}
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
logger.log("error", "ERROR JOINING ROOM => " + err)
|
logger.log("error", "ERROR JOINING ROOM => " + err)
|
||||||
@@ -441,6 +466,7 @@ class OcrccBot {
|
|||||||
member.userId !== this.config.BOT_USERID &&
|
member.userId !== this.config.BOT_USERID &&
|
||||||
this.localStorage.getItem(`${member.roomId}-waiting`)
|
this.localStorage.getItem(`${member.roomId}-waiting`)
|
||||||
) {
|
) {
|
||||||
|
try {
|
||||||
// make sure it's a facilitator joining
|
// make sure it's a facilitator joining
|
||||||
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID)
|
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID)
|
||||||
const members = Object.keys(roomMembers["joined"]);
|
const members = Object.keys(roomMembers["joined"]);
|
||||||
@@ -497,42 +523,112 @@ class OcrccBot {
|
|||||||
this.localStorage.setItem(`${member.roomId}-transcript`, filepath)
|
this.localStorage.setItem(`${member.roomId}-transcript`, filepath)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} catch(err) {
|
||||||
|
logger.log("error", `ERROR WHEN FACILITATOR JOINED ROOM ==> ${err}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
member.membership === "leave" &&
|
member.membership === "leave" &&
|
||||||
member.userId !== this.config.BOT_USERID
|
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)
|
const room = this.client.getRoom(member.roomId)
|
||||||
if (!room) return
|
if (!room) return;
|
||||||
|
|
||||||
|
const roomMembers = await room.getJoinedMembers() // array
|
||||||
|
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
|
// leave if there is nobody in the room
|
||||||
const memberCount = room.getJoinedMemberCount()
|
try {
|
||||||
|
const memberCount = roomMembers.length
|
||||||
if (memberCount === 1 && isBotInRoom) { // just the bot left
|
if (memberCount === 1 && isBotInRoom) { // just the bot left
|
||||||
logger.log("info", `LEAVING EMPTY ROOM ==> ${member.roomId}`);
|
logger.log("info", `LEAVING EMPTY ROOM: ${member.roomId}`);
|
||||||
this.deleteTranscript(member.userId, member.roomId);
|
this.deleteTranscript(member.userId, member.roomId);
|
||||||
this.localStorage.removeItem(`${member.roomId}-facilitator`)
|
this.localStorage.removeItem(`${member.roomId}-facilitator`)
|
||||||
this.localStorage.removeItem(`${member.roomId}-transcript`)
|
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) {
|
||||||
|
return logger.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// notify room if the facilitator has left
|
// notify room if the facilitator has left
|
||||||
|
try {
|
||||||
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`)
|
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`)
|
||||||
if (isBotInRoom && member.userId === facilitatorId) {
|
if (isBotInRoom && member.userId === facilitatorId) {
|
||||||
this.sendTextMessage(
|
this.sendTextMessage(
|
||||||
member.roomId,
|
member.roomId,
|
||||||
`${member.name} has left the chat.`
|
`${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}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// send signal to close the chat if there are no facilitators in the room
|
||||||
|
try {
|
||||||
|
const facilitators = facilitatorRoomMembers['joined']
|
||||||
|
let facilitatorInRoom = false;
|
||||||
|
|
||||||
|
roomMembers.forEach(member => {
|
||||||
|
if (member.userId !== this.config.BOT_USERID && Boolean(facilitators[member.userId])) {
|
||||||
|
facilitatorInRoom = true
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!facilitatorInRoom) {
|
||||||
|
logger.log("info", `NO FACILITATORS LEFT, SENDING SIGNAL TO END CHAT`);
|
||||||
|
this.sendBotSignal(member.roomId, BOT_SIGNAL_END_CHAT)
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch(err) {
|
||||||
|
logger.log("error", `ERROR SENDING BOT SIGNAL ==> ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setTimeoutforFacilitator(roomId) {
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
setInactivityTimeout(roomId) {
|
||||||
|
const oldTimeout = this.inactivityTimers[roomId];
|
||||||
|
|
||||||
|
if (oldTimeout) {
|
||||||
|
clearTimeout(oldTimeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
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.`
|
||||||
|
);
|
||||||
|
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
|
||||||
|
}, this.config.MAX_INACTIVE)
|
||||||
|
|
||||||
|
this.inactivityTimers[roomId] = newTimeout;
|
||||||
|
}
|
||||||
|
|
||||||
async setMessageListeners() {
|
async setMessageListeners() {
|
||||||
// encrypted messages
|
// encrypted messages
|
||||||
this.client.on("Event.decrypted", (event, err) => {
|
this.client.on("Event.decrypted", (event, err) => {
|
||||||
@@ -551,23 +647,23 @@ class OcrccBot {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async leaveOldRooms() {
|
async sendBotSignal (roomId, signal, args) {
|
||||||
const roomData = await this.client.getJoinedRooms()
|
let content = {
|
||||||
|
signal: signal,
|
||||||
roomData["joined_rooms"].forEach(async roomId => {
|
args: args,
|
||||||
try {
|
}
|
||||||
await this.client.leave(roomId)
|
try {
|
||||||
} catch(err) {
|
await this.client.sendStateEvent(roomId, 'm.bot.signal', content)
|
||||||
logger.log('error', "ERROR LEAVING ROOM => " + err)
|
} catch(err) {
|
||||||
|
logger.log('error', "ERROR SENDING BOT SIGNAL => " + err)
|
||||||
}
|
}
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async start() {
|
async start() {
|
||||||
|
try {
|
||||||
const localStorage = this.createLocalStorage();
|
const localStorage = this.createLocalStorage();
|
||||||
this.localStorage = localStorage
|
this.localStorage = localStorage
|
||||||
|
|
||||||
try {
|
|
||||||
const auth = {
|
const auth = {
|
||||||
user: this.config.BOT_USERNAME,
|
user: this.config.BOT_USERNAME,
|
||||||
password: this.config.BOT_PASSWORD,
|
password: this.config.BOT_PASSWORD,
|
||||||
@@ -592,6 +688,7 @@ class OcrccBot {
|
|||||||
logger.log("info", `SYNC STATUS: ${state}`)
|
logger.log("info", `SYNC STATUS: ${state}`)
|
||||||
if (state === 'PREPARED') {
|
if (state === 'PREPARED') {
|
||||||
await this.deleteOldDevices()
|
await this.deleteOldDevices()
|
||||||
|
await this.leaveEmptyRooms()
|
||||||
await this.trackJoinedRooms()
|
await this.trackJoinedRooms()
|
||||||
await this.setMembershipListeners();
|
await this.setMembershipListeners();
|
||||||
await this.setMessageListeners();
|
await this.setMessageListeners();
|
||||||
|
|||||||
@@ -32,7 +32,8 @@ import {
|
|||||||
mockKick,
|
mockKick,
|
||||||
mockGetJoinedRoomMembers,
|
mockGetJoinedRoomMembers,
|
||||||
mockGetUser,
|
mockGetUser,
|
||||||
mockGetGroupUsers
|
mockGetGroupUsers,
|
||||||
|
mockSendStateEvent,
|
||||||
} from "matrix-js-sdk";
|
} from "matrix-js-sdk";
|
||||||
|
|
||||||
import OcrccBot from './bot'
|
import OcrccBot from './bot'
|
||||||
@@ -100,6 +101,7 @@ describe('OcrccBot', () => {
|
|||||||
mockSendTextMessage.mockClear()
|
mockSendTextMessage.mockClear()
|
||||||
mockAppendFileSync.mockClear()
|
mockAppendFileSync.mockClear()
|
||||||
mockGetGroupUsers.mockClear()
|
mockGetGroupUsers.mockClear()
|
||||||
|
mockSendStateEvent.mockClear()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
@@ -325,4 +327,17 @@ describe('OcrccBot', () => {
|
|||||||
expect(mockStartClient).toHaveBeenCalled()
|
expect(mockStartClient).toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
test('#sendBotSignal should send custom state event', () => {
|
||||||
|
const bot = new OcrccBot(botConfig)
|
||||||
|
bot.start()
|
||||||
|
const test_room_id = 'test_room_id'
|
||||||
|
const signal = 'END_CHAT'
|
||||||
|
|
||||||
|
bot.sendBotSignal(test_room_id, signal)
|
||||||
|
|
||||||
|
waitForExpect(() => {
|
||||||
|
expect(mockSendStateEvent).toHaveBeenCalledWith(test_room_id, 'm.bot.signal', { signal })
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
13
src/index.js
13
src/index.js
@@ -5,6 +5,7 @@ const KICK_REASON = "A facilitator has already joined this chat.";
|
|||||||
const BOT_ERROR_MESSAGE =
|
const BOT_ERROR_MESSAGE =
|
||||||
"Something went wrong on our end, please restart the chat and try again.";
|
"Something went wrong on our end, please restart the chat and try again.";
|
||||||
const MAX_RETRIES = 3;
|
const MAX_RETRIES = 3;
|
||||||
|
|
||||||
const {
|
const {
|
||||||
MATRIX_SERVER_URL,
|
MATRIX_SERVER_URL,
|
||||||
BOT_USERNAME,
|
BOT_USERNAME,
|
||||||
@@ -13,6 +14,9 @@ const {
|
|||||||
BOT_DISPLAY_NAME,
|
BOT_DISPLAY_NAME,
|
||||||
FACILITATOR_ROOM_ID,
|
FACILITATOR_ROOM_ID,
|
||||||
CAPTURE_TRANSCRIPTS,
|
CAPTURE_TRANSCRIPTS,
|
||||||
|
CHAT_NOT_AVAILABLE_MESSAGE,
|
||||||
|
MAX_WAIT_TIME,
|
||||||
|
MAX_INACTIVE,
|
||||||
} = process.env;
|
} = process.env;
|
||||||
|
|
||||||
const botConfig = {
|
const botConfig = {
|
||||||
@@ -27,9 +31,16 @@ const botConfig = {
|
|||||||
BOT_DISPLAY_NAME,
|
BOT_DISPLAY_NAME,
|
||||||
FACILITATOR_ROOM_ID,
|
FACILITATOR_ROOM_ID,
|
||||||
CAPTURE_TRANSCRIPTS,
|
CAPTURE_TRANSCRIPTS,
|
||||||
|
CHAT_NOT_AVAILABLE_MESSAGE,
|
||||||
|
MAX_WAIT_TIME,
|
||||||
|
MAX_INACTIVE,
|
||||||
}
|
}
|
||||||
|
|
||||||
import OcrccBot from './bot'
|
import OcrccBot from './bot'
|
||||||
|
|
||||||
const bot = new OcrccBot(botConfig);
|
const bot = new OcrccBot(botConfig);
|
||||||
bot.start();
|
try {
|
||||||
|
bot.start();
|
||||||
|
} catch(err) {
|
||||||
|
console.log("AAAAAAAAAAAAA", err)
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user