Compare commits
12 Commits
feature/ad
...
v1.1.4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13dd515522 | ||
|
|
391bd22121 | ||
|
|
5ac3b9d367 | ||
|
|
f8a1698c56 | ||
|
|
4cddeae508 | ||
|
|
a323602a1d | ||
|
|
21a15c5efc | ||
|
|
16c9fd4148 | ||
|
|
f7a9851b7d | ||
|
|
74a1e29f1b | ||
|
|
b35bcd7dc7 | ||
|
|
189140e1f9 |
@@ -4,4 +4,4 @@ BOT_USERNAME=
|
|||||||
BOT_PASSWORD=
|
BOT_PASSWORD=
|
||||||
BOT_USERID=
|
BOT_USERID=
|
||||||
FACILITATOR_ROOM_ID=
|
FACILITATOR_ROOM_ID=
|
||||||
CHAT_OFFLINE_MESSAGE=
|
CAPTURE_TRANSCRIPTS
|
||||||
153
dist/bot.js
vendored
153
dist/bot.js
vendored
@@ -28,7 +28,6 @@ global.Olm = require("olm");
|
|||||||
class OcrccBot {
|
class OcrccBot {
|
||||||
constructor(botConfig) {
|
constructor(botConfig) {
|
||||||
this.config = botConfig;
|
this.config = botConfig;
|
||||||
this.awaitingFacilitator = {};
|
|
||||||
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
|
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
|
||||||
this.joinedRooms = [];
|
this.joinedRooms = [];
|
||||||
}
|
}
|
||||||
@@ -54,11 +53,38 @@ class OcrccBot {
|
|||||||
this.sendMessage(roomId, content);
|
this.sendMessage(roomId, content);
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendMessage(roomId, content) {
|
async sendNotice(roomId, message) {
|
||||||
_logger.default.log("info", `SENDING MESSAGE: ${content.body}`);
|
_logger.default.log("info", `SENDING *NOTICE*: ${message}`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.client.sendNotice(roomId, message);
|
||||||
|
} catch (err) {
|
||||||
|
switch (err["name"]) {
|
||||||
|
case "UnknownDeviceError":
|
||||||
|
Object.keys(err.devices).forEach(userId => {
|
||||||
|
Object.keys(err.devices[userId]).map(async deviceId => {
|
||||||
|
try {
|
||||||
|
await this.client.setDeviceVerified(userId, deviceId, true);
|
||||||
|
} catch (err) {
|
||||||
|
_logger.default.log("error", `ERROR VERIFYING DEVICE: ${err}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await this.sendNotice(roomId, message);
|
||||||
|
|
||||||
|
default:
|
||||||
|
_logger.default.log("error", `ERROR SENDING *NOTICE*: ${err}`);
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async sendMessage(roomId, content) {
|
||||||
try {
|
try {
|
||||||
await this.client.sendMessage(roomId, content);
|
await this.client.sendMessage(roomId, content);
|
||||||
|
|
||||||
|
_logger.default.log("info", `SENT MESSAGE: ${content.body}`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
switch (err["name"]) {
|
switch (err["name"]) {
|
||||||
case "UnknownDeviceError":
|
case "UnknownDeviceError":
|
||||||
@@ -101,25 +127,26 @@ class OcrccBot {
|
|||||||
|
|
||||||
async inviteFacilitators(roomId) {
|
async inviteFacilitators(roomId) {
|
||||||
this.localStorage.setItem(`${roomId}-waiting`, 'true');
|
this.localStorage.setItem(`${roomId}-waiting`, 'true');
|
||||||
let chatOffline = true;
|
let invitations = [];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data = await this.client.getGroupUsers(this.config.FACILITATOR_GROUP_ID);
|
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
|
||||||
const members = data.chunk;
|
const members = Object.keys(roomMembers["joined"]);
|
||||||
members.forEach(member => {
|
members.forEach(memberId => {
|
||||||
const memberId = member.user_id;
|
|
||||||
const user = this.client.getUser(memberId);
|
const user = this.client.getUser(memberId);
|
||||||
|
|
||||||
if (user && user.presence === "online" && memberId !== this.config.BOT_USERID) {
|
if (user && user.presence !== "offline" && memberId !== this.config.BOT_USERID) {
|
||||||
chatOffline = false;
|
invitations.push(memberId);
|
||||||
this.inviteUserToRoom(roomId, memberId);
|
this.inviteUserToRoom(roomId, memberId);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (chatOffline) {
|
if (invitations.length > 0) {
|
||||||
|
this.localStorage.setItem(`${roomId}-invitations`, invitations);
|
||||||
|
} else {
|
||||||
_logger.default.log('info', "NO FACILITATORS ONLINE");
|
_logger.default.log('info', "NO FACILITATORS ONLINE");
|
||||||
|
|
||||||
this.sendTextMessage(roomId, this.config.CHAT_OFFLINE_MESSAGE);
|
this.sendNotice(roomId, "CHAT_OFFLINE");
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.handleBotCrash(roomId, err);
|
this.handleBotCrash(roomId, err);
|
||||||
@@ -132,12 +159,13 @@ class OcrccBot {
|
|||||||
this.localStorage.removeItem(`${roomId}-waiting`);
|
this.localStorage.removeItem(`${roomId}-waiting`);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const groupUsers = await this.client.getGroupUsers(this.config.FACILITATOR_GROUP_ID);
|
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
|
||||||
const roomMembers = await this.client.getJoinedRoomMembers(roomId);
|
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId);
|
||||||
const membersIds = Object.keys(roomMembers["joined"]);
|
const roomMembersIds = Object.keys(supportRoomMembers["joined"]);
|
||||||
const facilitatorsIds = groupUsers.chunk.map(f => f.user_id);
|
const facilitatorsIds = Object.keys(facilitatorsRoomMembers["joined"]);
|
||||||
|
if (!roomMembersIds || !facilitatorsIds) return;
|
||||||
facilitatorsIds.forEach(f => {
|
facilitatorsIds.forEach(f => {
|
||||||
if (!membersIds.includes(f)) {
|
if (!roomMembersIds.includes(f)) {
|
||||||
this.kickUserFromRoom(roomId, f);
|
this.kickUserFromRoom(roomId, f);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -212,6 +240,10 @@ class OcrccBot {
|
|||||||
this.sendTranscript(senderId, roomId);
|
this.sendTranscript(senderId, roomId);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
|
case "delete transcript":
|
||||||
|
this.deleteTranscript(senderId, roomId);
|
||||||
|
break;
|
||||||
|
|
||||||
case "hi":
|
case "hi":
|
||||||
const responses = ["Hi!", "Hello", "Hey :)", "Hi there", "Bleep bloop"];
|
const responses = ["Hi!", "Hello", "Hey :)", "Hi there", "Bleep bloop"];
|
||||||
const message = responses[Math.floor(Math.random() * responses.length)];
|
const message = responses[Math.floor(Math.random() * responses.length)];
|
||||||
@@ -258,16 +290,25 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const filename = path.basename(transcriptFile) || "Transcript";
|
const filename = path.basename(transcriptFile) || "Transcript";
|
||||||
const stream = fs.createReadStream(transcriptFile);
|
const file = fs.readFileSync(transcriptFile);
|
||||||
const contentUrl = await this.client.uploadContent({
|
const stats = fs.statSync(transcriptFile);
|
||||||
stream: stream,
|
const url = await this.client.uploadContent(file, {
|
||||||
|
rawResponse: false,
|
||||||
name: filename
|
name: filename
|
||||||
});
|
});
|
||||||
|
|
||||||
|
_logger.default.log('info', url);
|
||||||
|
|
||||||
const content = {
|
const content = {
|
||||||
msgtype: "m.file",
|
msgtype: "m.file",
|
||||||
body: filename,
|
body: filename,
|
||||||
url: JSON.parse(contentUrl).content_uri,
|
info: {
|
||||||
showToUser: senderId
|
size: stats.size,
|
||||||
|
mimetype: 'text/plain'
|
||||||
|
},
|
||||||
|
url: url.content_uri,
|
||||||
|
showToUser: senderId,
|
||||||
|
mimetype: 'text/plain'
|
||||||
};
|
};
|
||||||
this.sendMessage(roomId, content);
|
this.sendMessage(roomId, content);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -277,6 +318,30 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
deleteTranscript(senderId, roomId) {
|
||||||
|
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
|
||||||
|
|
||||||
|
if (!transcriptFile) {
|
||||||
|
return this.sendTextMessage(roomId, "There is no transcript for this chat.", senderId);
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.unlink(transcriptFile, err => {
|
||||||
|
if (err) {
|
||||||
|
_logger.default.log('error', "UNABLE TO DELETE TRANSCRIPT FILE => " + transcriptFile);
|
||||||
|
|
||||||
|
_logger.default.log('error', err);
|
||||||
|
|
||||||
|
return this.sendTextMessage(roomId, `There was an error deleting the transcript: ${err}`, senderId);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.localStorage.removeItem(`${roomId}-transcript`);
|
||||||
|
|
||||||
|
_logger.default.log('info', "DELETED TRANSCRIPT FILE => " + transcriptFile);
|
||||||
|
|
||||||
|
this.sendTextMessage(roomId, `The transcript file has been deleted.`, senderId);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async deleteOldDevices() {
|
async deleteOldDevices() {
|
||||||
const currentDeviceId = this.client.getDeviceId();
|
const currentDeviceId = this.client.getDeviceId();
|
||||||
const deviceData = await this.client.getDevices();
|
const deviceData = await this.client.getDevices();
|
||||||
@@ -316,20 +381,35 @@ class OcrccBot {
|
|||||||
this.client.on("RoomMember.membership", async (event, member) => {
|
this.client.on("RoomMember.membership", async (event, member) => {
|
||||||
if (member.membership === "invite" && member.userId === this.config.BOT_USERID && !this.joinedRooms.includes(member.roomId)) {
|
if (member.membership === "invite" && member.userId === this.config.BOT_USERID && !this.joinedRooms.includes(member.roomId)) {
|
||||||
try {
|
try {
|
||||||
|
const roomData = await this.client.getJoinedRooms();
|
||||||
|
const joinedRooms = roomData["joined_rooms"];
|
||||||
|
|
||||||
|
if (!joinedRooms.includes(member.roomId)) {
|
||||||
const room = await this.client.joinRoom(member.roomId);
|
const room = await this.client.joinRoom(member.roomId);
|
||||||
|
|
||||||
_logger.default.log("info", "AUTO JOINED ROOM => " + room.roomId);
|
_logger.default.log("info", "AUTO JOINED ROOM => " + room.roomId);
|
||||||
|
|
||||||
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, `A support seeker requested a chat (Room ID: ${room.roomId})`);
|
const currentDate = new Date();
|
||||||
|
const chatDate = currentDate.toLocaleDateString();
|
||||||
|
const chatTime = currentDate.toLocaleTimeString();
|
||||||
|
const roomId = room.roomId.split(':')[0];
|
||||||
|
const notification = `Incoming support chat at ${chatTime} (room ID: ${roomId})`;
|
||||||
|
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification);
|
||||||
this.inviteFacilitators(room.roomId);
|
this.inviteFacilitators(room.roomId);
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
_logger.default.log("error", "ERROR JOINING ROOM => " + err);
|
_logger.default.log("error", "ERROR JOINING ROOM => " + err);
|
||||||
}
|
}
|
||||||
} // When a facilitator joins a support session, make them a moderator
|
}
|
||||||
// revoke the other invitations
|
|
||||||
|
|
||||||
|
|
||||||
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`)) {
|
||||||
|
// 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);
|
this.localStorage.setItem(`${member.roomId}-facilitator`, member.userId);
|
||||||
const event = {
|
const event = {
|
||||||
getType: () => {
|
getType: () => {
|
||||||
@@ -344,10 +424,17 @@ class OcrccBot {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
this.client.setPowerLevel(member.roomId, member.userId, 50, event);
|
this.client.setPowerLevel(member.roomId, member.userId, 50, event); // send notification to Support Chat Notifications room
|
||||||
this.sendTextMessage(member.roomId, `${member.name} has joined the chat.`);
|
|
||||||
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, `${member.name} joined the chat (Room ID: ${member.roomId})`);
|
const currentDate = new Date();
|
||||||
this.uninviteFacilitators(member.roomId);
|
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) {
|
if (this.config.CAPTURE_TRANSCRIPTS) {
|
||||||
const currentDate = new Date();
|
const currentDate = new Date();
|
||||||
@@ -365,6 +452,7 @@ class OcrccBot {
|
|||||||
this.localStorage.setItem(`${member.roomId}-transcript`, filepath);
|
this.localStorage.setItem(`${member.roomId}-transcript`, filepath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (member.membership === "leave" && member.userId !== this.config.BOT_USERID) {
|
if (member.membership === "leave" && member.userId !== this.config.BOT_USERID) {
|
||||||
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`);
|
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`);
|
||||||
@@ -379,12 +467,13 @@ class OcrccBot {
|
|||||||
const memberCount = room.getJoinedMemberCount();
|
const memberCount = room.getJoinedMemberCount();
|
||||||
|
|
||||||
if (memberCount === 1) {
|
if (memberCount === 1) {
|
||||||
// just the bot
|
// just the bot left
|
||||||
_logger.default.log("info", `LEAVING EMPTY ROOM ==> ${member.roomId}`);
|
_logger.default.log("info", `LEAVING EMPTY ROOM ==> ${member.roomId}`);
|
||||||
|
|
||||||
this.client.leave(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`);
|
||||||
|
this.client.leave(member.roomId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
58
dist/bot.test.js
vendored
58
dist/bot.test.js
vendored
@@ -18,6 +18,36 @@ var _bot = _interopRequireDefault(require("./bot"));
|
|||||||
|
|
||||||
require('dotenv').config();
|
require('dotenv').config();
|
||||||
|
|
||||||
|
const ENCRYPTION_CONFIG = {
|
||||||
|
algorithm: "m.megolm.v1.aes-sha2"
|
||||||
|
};
|
||||||
|
const KICK_REASON = "A facilitator has already joined this chat.";
|
||||||
|
const BOT_ERROR_MESSAGE = "Something went wrong on our end, please restart the chat and try again.";
|
||||||
|
const MAX_RETRIES = 3;
|
||||||
|
const {
|
||||||
|
MATRIX_SERVER_URL,
|
||||||
|
BOT_USERNAME,
|
||||||
|
BOT_USERID,
|
||||||
|
BOT_PASSWORD,
|
||||||
|
BOT_DISPLAY_NAME,
|
||||||
|
FACILITATOR_ROOM_ID,
|
||||||
|
CHAT_OFFLINE_MESSAGE,
|
||||||
|
CAPTURE_TRANSCRIPTS
|
||||||
|
} = process.env;
|
||||||
|
const botConfig = {
|
||||||
|
ENCRYPTION_CONFIG,
|
||||||
|
KICK_REASON,
|
||||||
|
BOT_ERROR_MESSAGE,
|
||||||
|
MAX_RETRIES,
|
||||||
|
MATRIX_SERVER_URL,
|
||||||
|
BOT_USERNAME,
|
||||||
|
BOT_USERID,
|
||||||
|
BOT_PASSWORD,
|
||||||
|
BOT_DISPLAY_NAME,
|
||||||
|
FACILITATOR_ROOM_ID,
|
||||||
|
CHAT_OFFLINE_MESSAGE,
|
||||||
|
CAPTURE_TRANSCRIPTS
|
||||||
|
};
|
||||||
const mockAppendFileSync = jest.fn();
|
const mockAppendFileSync = jest.fn();
|
||||||
fs.appendFileSync = mockAppendFileSync;
|
fs.appendFileSync = mockAppendFileSync;
|
||||||
describe('OcrccBot', () => {
|
describe('OcrccBot', () => {
|
||||||
@@ -75,19 +105,17 @@ describe('OcrccBot', () => {
|
|||||||
_matrixJsSdk.mockGetGroupUsers.mockClear();
|
_matrixJsSdk.mockGetGroupUsers.mockClear();
|
||||||
});
|
});
|
||||||
test('constructor should inititialize class variables', () => {
|
test('constructor should inititialize class variables', () => {
|
||||||
const bot = new _bot.default();
|
const bot = new _bot.default(botConfig);
|
||||||
expect(bot.joinedRooms).toEqual([]);
|
expect(bot.joinedRooms).toEqual([]);
|
||||||
expect(bot.awaitingFacilitator).toEqual({});
|
|
||||||
expect(bot.activeChatrooms).toEqual({});
|
|
||||||
});
|
});
|
||||||
test('#createLocalStorage should have correct storage location', () => {
|
test('#createLocalStorage should have correct storage location', () => {
|
||||||
const bot = new _bot.default();
|
const bot = new _bot.default(botConfig);
|
||||||
const localStorage = bot.createLocalStorage();
|
const localStorage = bot.createLocalStorage();
|
||||||
const localStoragePath = path.resolve(path.join(os.homedir(), ".local-storage", `matrix-chatbot-${process.env.BOT_USERNAME}`));
|
const localStoragePath = path.resolve(path.join(os.homedir(), ".local-storage", `matrix-chatbot-${process.env.BOT_USERNAME}`));
|
||||||
expect(localStorage._location).toBe(localStoragePath);
|
expect(localStorage._location).toBe(localStoragePath);
|
||||||
});
|
});
|
||||||
test('#sendMessage should send a text message', () => {
|
test('#sendMessage should send a text message', () => {
|
||||||
const bot = new _bot.default();
|
const bot = new _bot.default(botConfig);
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
@@ -103,7 +131,7 @@ describe('OcrccBot', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#inviteUserToRoom should add member to room and retry on rate limit error', () => {
|
test('#inviteUserToRoom should add member to room and retry on rate limit error', () => {
|
||||||
const bot = new _bot.default();
|
const bot = new _bot.default(botConfig);
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
@@ -114,7 +142,7 @@ describe('OcrccBot', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#kickUserFromRoom should remove member from room and retry on rate limit error', () => {
|
test('#kickUserFromRoom should remove member from room and retry on rate limit error', () => {
|
||||||
const bot = new _bot.default();
|
const bot = new _bot.default(botConfig);
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
@@ -125,7 +153,7 @@ describe('OcrccBot', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#inviteFacilitators should invite all members from Facilitator room', () => {
|
test('#inviteFacilitators should invite all members from Facilitator room', () => {
|
||||||
const bot = new _bot.default();
|
const bot = new _bot.default(botConfig);
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
@@ -142,7 +170,7 @@ describe('OcrccBot', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#uninviteFacilitators should remove all members that have not accepted the invite', () => {
|
test('#uninviteFacilitators should remove all members that have not accepted the invite', () => {
|
||||||
const bot = new _bot.default();
|
const bot = new _bot.default(botConfig);
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
@@ -159,7 +187,7 @@ describe('OcrccBot', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#handleBotCrash should notify rooms', () => {
|
test('#handleBotCrash should notify rooms', () => {
|
||||||
const bot = new _bot.default();
|
const bot = new _bot.default(botConfig);
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
@@ -173,11 +201,9 @@ describe('OcrccBot', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#writeToTranscript should parse event and write to transcript file', () => {
|
test('#writeToTranscript should parse event and write to transcript file', () => {
|
||||||
const bot = new _bot.default();
|
const bot = new _bot.default(botConfig);
|
||||||
bot.start();
|
bot.start();
|
||||||
bot.activeChatrooms['test_room_id'] = {
|
bot.localStorage.setItem(`test_room_id-transcript`, '__mocks__/test_transcript.txt');
|
||||||
transcriptFile: '__mocks__/test_transcript.txt'
|
|
||||||
};
|
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
@@ -199,7 +225,7 @@ describe('OcrccBot', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
test('#deleteOldDevices should delete old sessions', () => {
|
test('#deleteOldDevices should delete old sessions', () => {
|
||||||
const bot = new _bot.default();
|
const bot = new _bot.default(botConfig);
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockStartClient).toHaveBeenCalled();
|
||||||
@@ -217,7 +243,7 @@ describe('OcrccBot', () => {
|
|||||||
}); // TODO test listeners for membership events and message events
|
}); // TODO test listeners for membership events and message events
|
||||||
|
|
||||||
test('#start should start bot and set up listeners', () => {
|
test('#start should start bot and set up listeners', () => {
|
||||||
const bot = new _bot.default();
|
const bot = new _bot.default(botConfig);
|
||||||
bot.start();
|
bot.start();
|
||||||
(0, _waitForExpect.default)(() => {
|
(0, _waitForExpect.default)(() => {
|
||||||
expect(_matrixJsSdk.mockLogin).toHaveBeenCalled();
|
expect(_matrixJsSdk.mockLogin).toHaveBeenCalled();
|
||||||
|
|||||||
4
dist/index.js
vendored
4
dist/index.js
vendored
@@ -18,9 +18,7 @@ const {
|
|||||||
BOT_USERID,
|
BOT_USERID,
|
||||||
BOT_PASSWORD,
|
BOT_PASSWORD,
|
||||||
BOT_DISPLAY_NAME,
|
BOT_DISPLAY_NAME,
|
||||||
FACILITATOR_GROUP_ID,
|
|
||||||
FACILITATOR_ROOM_ID,
|
FACILITATOR_ROOM_ID,
|
||||||
CHAT_OFFLINE_MESSAGE,
|
|
||||||
CAPTURE_TRANSCRIPTS
|
CAPTURE_TRANSCRIPTS
|
||||||
} = process.env;
|
} = process.env;
|
||||||
const botConfig = {
|
const botConfig = {
|
||||||
@@ -33,9 +31,7 @@ const botConfig = {
|
|||||||
BOT_USERID,
|
BOT_USERID,
|
||||||
BOT_PASSWORD,
|
BOT_PASSWORD,
|
||||||
BOT_DISPLAY_NAME,
|
BOT_DISPLAY_NAME,
|
||||||
FACILITATOR_GROUP_ID,
|
|
||||||
FACILITATOR_ROOM_ID,
|
FACILITATOR_ROOM_ID,
|
||||||
CHAT_OFFLINE_MESSAGE,
|
|
||||||
CAPTURE_TRANSCRIPTS
|
CAPTURE_TRANSCRIPTS
|
||||||
};
|
};
|
||||||
const bot = new _bot.default(botConfig);
|
const bot = new _bot.default(botConfig);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "safesupport-bot",
|
"name": "private-safesupport-bot",
|
||||||
"version": "1.0.0",
|
"version": "1.1.4",
|
||||||
"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": {
|
||||||
@@ -13,7 +13,7 @@
|
|||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"dotenv": "^8.2.0",
|
"dotenv": "^8.2.0",
|
||||||
"matrix-js-sdk": "^5.0.1",
|
"matrix-js-sdk": "^6.2.1",
|
||||||
"node-localstorage": "^2.1.5",
|
"node-localstorage": "^2.1.5",
|
||||||
"olm": "https://packages.matrix.org/npm/olm/olm-3.1.4.tgz",
|
"olm": "https://packages.matrix.org/npm/olm/olm-3.1.4.tgz",
|
||||||
"uuidv4": "^6.0.2",
|
"uuidv4": "^6.0.2",
|
||||||
|
|||||||
96
src/bot.js
96
src/bot.js
@@ -64,9 +64,9 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async sendMessage(roomId, content) {
|
async sendMessage(roomId, content) {
|
||||||
logger.log("info", `SENDING MESSAGE: ${content.body}`)
|
|
||||||
try {
|
try {
|
||||||
await this.client.sendMessage(roomId, content)
|
await this.client.sendMessage(roomId, content)
|
||||||
|
logger.log("info", `SENT MESSAGE: ${content.body}`)
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
switch (err["name"]) {
|
switch (err["name"]) {
|
||||||
case "UnknownDeviceError":
|
case "UnknownDeviceError":
|
||||||
@@ -106,29 +106,29 @@ class OcrccBot {
|
|||||||
|
|
||||||
async inviteFacilitators(roomId) {
|
async inviteFacilitators(roomId) {
|
||||||
this.localStorage.setItem(`${roomId}-waiting`, 'true')
|
this.localStorage.setItem(`${roomId}-waiting`, 'true')
|
||||||
let chatOffline = true;
|
let invitations = []
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data = await this.client.getGroupUsers(this.config.FACILITATOR_GROUP_ID)
|
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID)
|
||||||
const members = data.chunk
|
const members = Object.keys(roomMembers["joined"]);
|
||||||
|
|
||||||
members.forEach(member => {
|
members.forEach(memberId => {
|
||||||
const memberId = member.user_id;
|
|
||||||
const user = this.client.getUser(memberId);
|
const user = this.client.getUser(memberId);
|
||||||
if (
|
if (
|
||||||
user &&
|
user &&
|
||||||
user.presence === "online" &&
|
(user.presence !== "offline") &&
|
||||||
memberId !== this.config.BOT_USERID
|
memberId !== this.config.BOT_USERID
|
||||||
) {
|
) {
|
||||||
chatOffline = false;
|
invitations.push(memberId)
|
||||||
this.inviteUserToRoom(roomId, memberId);
|
this.inviteUserToRoom(roomId, memberId);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (chatOffline) {
|
if (invitations.length > 0) {
|
||||||
|
this.localStorage.setItem(`${roomId}-invitations`, invitations)
|
||||||
|
} else {
|
||||||
logger.log('info', "NO FACILITATORS ONLINE")
|
logger.log('info', "NO FACILITATORS ONLINE")
|
||||||
this.sendTextMessage(roomId, this.config.CHAT_OFFLINE_MESSAGE);
|
this.sendNotice(roomId, "CHAT_OFFLINE")
|
||||||
this.sendNotice(roomId, "Chat is offline")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
@@ -142,18 +142,17 @@ class OcrccBot {
|
|||||||
this.localStorage.removeItem(`${roomId}-waiting`)
|
this.localStorage.removeItem(`${roomId}-waiting`)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const groupUsers = await this.client.getGroupUsers(this.config.FACILITATOR_GROUP_ID)
|
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID)
|
||||||
const roomMembers = await this.client.getJoinedRoomMembers(roomId)
|
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId)
|
||||||
|
|
||||||
const roomMemberIds = Object.keys(roomMembers["joined"]);
|
const roomMembersIds = Object.keys(supportRoomMembers["joined"]);
|
||||||
const groupMemberIds = groupUsers["chunk"]
|
const facilitatorsIds = Object.keys(facilitatorsRoomMembers["joined"]);
|
||||||
|
|
||||||
if (!roomMemberIds || !groupMemberIds) return;
|
if (!roomMembersIds || !facilitatorsIds) return;
|
||||||
|
|
||||||
const facilitatorsIds = groupMemberIds.map(f => f.user_id);
|
|
||||||
|
|
||||||
facilitatorsIds.forEach(f => {
|
facilitatorsIds.forEach(f => {
|
||||||
if (!roomMemberIds.includes(f)) {
|
if (!roomMembersIds.includes(f)) {
|
||||||
this.kickUserFromRoom(roomId, f);
|
this.kickUserFromRoom(roomId, f);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -291,18 +290,22 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const filename = path.basename(transcriptFile) || "Transcript";
|
const filename = path.basename(transcriptFile) || "Transcript";
|
||||||
const stream = fs.createReadStream(transcriptFile);
|
const file = fs.readFileSync(transcriptFile);
|
||||||
|
const stats = fs.statSync(transcriptFile);
|
||||||
|
|
||||||
const contentUrl = await this.client.uploadContent({
|
const url = await this.client.uploadContent(file, { rawResponse: false, name: filename })
|
||||||
stream: stream,
|
logger.log('info', url)
|
||||||
name: filename
|
|
||||||
})
|
|
||||||
|
|
||||||
const content = {
|
const content = {
|
||||||
msgtype: "m.file",
|
msgtype: "m.file",
|
||||||
body: filename,
|
body: filename,
|
||||||
url: JSON.parse(contentUrl).content_uri,
|
info: {
|
||||||
showToUser: senderId
|
size: stats.size,
|
||||||
|
mimetype: 'text/plain'
|
||||||
|
},
|
||||||
|
url: url.content_uri,
|
||||||
|
showToUser: senderId,
|
||||||
|
mimetype: 'text/plain'
|
||||||
};
|
};
|
||||||
|
|
||||||
this.sendMessage(roomId, content);
|
this.sendMessage(roomId, content);
|
||||||
@@ -386,25 +389,36 @@ class OcrccBot {
|
|||||||
!this.joinedRooms.includes(member.roomId)
|
!this.joinedRooms.includes(member.roomId)
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
|
const roomData = await this.client.getJoinedRooms()
|
||||||
|
const joinedRooms = roomData["joined_rooms"]
|
||||||
|
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)
|
||||||
this.sendTextMessage(
|
const currentDate = new Date()
|
||||||
this.config.FACILITATOR_ROOM_ID,
|
const chatDate = currentDate.toLocaleDateString()
|
||||||
`A support seeker requested a chat (Room ID: ${room.roomId})`
|
const chatTime = currentDate.toLocaleTimeString()
|
||||||
);
|
const roomId = room.roomId.split(':')[0]
|
||||||
|
const notification = `Incoming support chat at ${chatTime} (room ID: ${roomId})`
|
||||||
|
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification);
|
||||||
this.inviteFacilitators(room.roomId)
|
this.inviteFacilitators(room.roomId)
|
||||||
|
}
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
logger.log("error", "ERROR JOINING ROOM => " + err)
|
logger.log("error", "ERROR JOINING ROOM => " + err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// When a facilitator joins a support session, make them a moderator
|
|
||||||
// revoke the other invitations
|
|
||||||
if (
|
if (
|
||||||
member.membership === "join" &&
|
member.membership === "join" &&
|
||||||
member.userId !== this.config.BOT_USERID &&
|
member.userId !== this.config.BOT_USERID &&
|
||||||
this.localStorage.getItem(`${member.roomId}-waiting`)
|
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)
|
||||||
|
|
||||||
|
if (isFacilitator) {
|
||||||
|
// made facilitator a moderator in the room
|
||||||
this.localStorage.setItem(`${member.roomId}-facilitator`, member.userId)
|
this.localStorage.setItem(`${member.roomId}-facilitator`, member.userId)
|
||||||
const event = {
|
const event = {
|
||||||
getType: () => {
|
getType: () => {
|
||||||
@@ -420,15 +434,24 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
this.client.setPowerLevel(member.roomId, member.userId, 50, event);
|
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(
|
this.sendTextMessage(
|
||||||
member.roomId,
|
member.roomId,
|
||||||
`${member.name} has joined the chat.`
|
`${member.name} has joined the chat.`
|
||||||
);
|
);
|
||||||
this.sendTextMessage(
|
|
||||||
this.config.FACILITATOR_ROOM_ID,
|
// revoke the other invitations
|
||||||
`${member.name} joined the chat (Room ID: ${member.roomId})`
|
|
||||||
);
|
|
||||||
this.uninviteFacilitators(member.roomId);
|
this.uninviteFacilitators(member.roomId);
|
||||||
|
|
||||||
|
// set transcript file
|
||||||
if (this.config.CAPTURE_TRANSCRIPTS) {
|
if (this.config.CAPTURE_TRANSCRIPTS) {
|
||||||
const currentDate = new Date();
|
const currentDate = new Date();
|
||||||
const dateOpts = {
|
const dateOpts = {
|
||||||
@@ -445,6 +468,7 @@ class OcrccBot {
|
|||||||
this.localStorage.setItem(`${member.roomId}-transcript`, filepath)
|
this.localStorage.setItem(`${member.roomId}-transcript`, filepath)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
member.membership === "leave" &&
|
member.membership === "leave" &&
|
||||||
@@ -472,7 +496,7 @@ class OcrccBot {
|
|||||||
this.client.leave(member.roomId)
|
this.client.leave(member.roomId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async setMessageListeners() {
|
async setMessageListeners() {
|
||||||
|
|||||||
@@ -48,7 +48,6 @@ const {
|
|||||||
BOT_USERID,
|
BOT_USERID,
|
||||||
BOT_PASSWORD,
|
BOT_PASSWORD,
|
||||||
BOT_DISPLAY_NAME,
|
BOT_DISPLAY_NAME,
|
||||||
FACILITATOR_GROUP_ID,
|
|
||||||
FACILITATOR_ROOM_ID,
|
FACILITATOR_ROOM_ID,
|
||||||
CHAT_OFFLINE_MESSAGE,
|
CHAT_OFFLINE_MESSAGE,
|
||||||
CAPTURE_TRANSCRIPTS
|
CAPTURE_TRANSCRIPTS
|
||||||
@@ -64,7 +63,6 @@ const botConfig = {
|
|||||||
BOT_USERID,
|
BOT_USERID,
|
||||||
BOT_PASSWORD,
|
BOT_PASSWORD,
|
||||||
BOT_DISPLAY_NAME,
|
BOT_DISPLAY_NAME,
|
||||||
FACILITATOR_GROUP_ID,
|
|
||||||
FACILITATOR_ROOM_ID,
|
FACILITATOR_ROOM_ID,
|
||||||
CHAT_OFFLINE_MESSAGE,
|
CHAT_OFFLINE_MESSAGE,
|
||||||
CAPTURE_TRANSCRIPTS
|
CAPTURE_TRANSCRIPTS
|
||||||
|
|||||||
@@ -11,10 +11,8 @@ const {
|
|||||||
BOT_USERID,
|
BOT_USERID,
|
||||||
BOT_PASSWORD,
|
BOT_PASSWORD,
|
||||||
BOT_DISPLAY_NAME,
|
BOT_DISPLAY_NAME,
|
||||||
FACILITATOR_GROUP_ID,
|
|
||||||
FACILITATOR_ROOM_ID,
|
FACILITATOR_ROOM_ID,
|
||||||
CHAT_OFFLINE_MESSAGE,
|
CAPTURE_TRANSCRIPTS,
|
||||||
CAPTURE_TRANSCRIPTS
|
|
||||||
} = process.env;
|
} = process.env;
|
||||||
|
|
||||||
const botConfig = {
|
const botConfig = {
|
||||||
@@ -27,10 +25,8 @@ const botConfig = {
|
|||||||
BOT_USERID,
|
BOT_USERID,
|
||||||
BOT_PASSWORD,
|
BOT_PASSWORD,
|
||||||
BOT_DISPLAY_NAME,
|
BOT_DISPLAY_NAME,
|
||||||
FACILITATOR_GROUP_ID,
|
|
||||||
FACILITATOR_ROOM_ID,
|
FACILITATOR_ROOM_ID,
|
||||||
CHAT_OFFLINE_MESSAGE,
|
CAPTURE_TRANSCRIPTS,
|
||||||
CAPTURE_TRANSCRIPTS
|
|
||||||
}
|
}
|
||||||
|
|
||||||
import OcrccBot from './bot'
|
import OcrccBot from './bot'
|
||||||
|
|||||||
@@ -3762,10 +3762,10 @@ map-visit@^1.0.0:
|
|||||||
dependencies:
|
dependencies:
|
||||||
object-visit "^1.0.0"
|
object-visit "^1.0.0"
|
||||||
|
|
||||||
matrix-js-sdk@^5.0.1:
|
matrix-js-sdk@^6.2.1:
|
||||||
version "5.1.0"
|
version "6.2.1"
|
||||||
resolved "https://registry.yarnpkg.com/matrix-js-sdk/-/matrix-js-sdk-5.1.0.tgz#9b3b02af227ecc2d0cc35fb7312c92b8a6754293"
|
resolved "https://registry.yarnpkg.com/matrix-js-sdk/-/matrix-js-sdk-6.2.1.tgz#d5f76491a650c0a36fcdd078cff59f2da96edd7b"
|
||||||
integrity sha512-IGRq5iACiKp3iIxAghwtdBPrbdgORowc0i8YuIMkZZMpRJDXnNaudt2BFwyQdukV7gvzz7F0sfxBUerySfOnKA==
|
integrity sha512-X12Y2SMg8MOJwE5P3VMsMV/mnQHOmyJkF+FZRida124w4B4tBJouaNxteYyYaH34w+wyaKGxuqEBXecfSpfvbw==
|
||||||
dependencies:
|
dependencies:
|
||||||
"@babel/runtime" "^7.8.3"
|
"@babel/runtime" "^7.8.3"
|
||||||
another-json "^0.2.0"
|
another-json "^0.2.0"
|
||||||
|
|||||||
Reference in New Issue
Block a user