Compare commits
No commits in common. "master" and "botsignal" have entirely different histories.
7
.env.sample
Normal file
7
.env.sample
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
MATRIX_SERVER_URL=
|
||||||
|
BOT_DISPLAY_NAME=
|
||||||
|
BOT_USERNAME=
|
||||||
|
BOT_PASSWORD=
|
||||||
|
BOT_USERID=
|
||||||
|
FACILITATOR_ROOM_ID=
|
||||||
|
CAPTURE_TRANSCRIPTS
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -3,4 +3,3 @@ node_modules
|
|||||||
*.log
|
*.log
|
||||||
__mocks__/test_transcript.txt
|
__mocks__/test_transcript.txt
|
||||||
transcripts/*.txt
|
transcripts/*.txt
|
||||||
config.json
|
|
@ -1,10 +1,5 @@
|
|||||||
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
|
||||||
|
26
README.md
26
README.md
@ -1,10 +1,19 @@
|
|||||||
# Safe Support Chat Bot
|
# Safe Support Chat Bot
|
||||||
|
|
||||||
A simple Matrix bot that handles inviting, uninviting, and notifying Riot users on the recieving end of the [Safe Support chatbox](https://github.com/Safe-Support-Chat/ocrcc-chatbox).
|
A simple Matrix bot that handles inviting, uninviting, and notifying Riot users on the recieving end of the [Safe Support chatbox](https://github.com/nomadic-labs/safesupport-chatbox).
|
||||||
|
|
||||||
The bot configuration file is `config.json`. It can also pull in user-set configurations from the Safe Support Chat Admin app. To do so, run the command `yarn setup` before starting the bot.
|
|
||||||
|
|
||||||
|
The bot can be configured with an `.env` file with the following variables:
|
||||||
|
|
||||||
|
```
|
||||||
|
MATRIX_SERVER_URL=
|
||||||
|
BOT_DISPLAY_NAME=
|
||||||
|
BOT_USERNAME=
|
||||||
|
BOT_PASSWORD=
|
||||||
|
BOT_USERID=
|
||||||
|
FACILITATOR_ROOM_ID=
|
||||||
|
CHAT_OFFLINE_MESSAGE=
|
||||||
|
CAPTURE_TRANSCRIPTS=
|
||||||
|
```
|
||||||
## What does the bot do?
|
## What does the bot do?
|
||||||
* The bot receives an invitation to every chatroom created by the embedded chatbox, and automatically accepts
|
* The bot receives an invitation to every chatroom created by the embedded chatbox, and automatically accepts
|
||||||
* Upon joining a new room, the bot invites all of the members of the Facilitators community
|
* Upon joining a new room, the bot invites all of the members of the Facilitators community
|
||||||
@ -30,7 +39,7 @@ If you prefer to develop locally instead of on Glitch:
|
|||||||
|
|
||||||
Clone the project
|
Clone the project
|
||||||
```
|
```
|
||||||
git clone https://github.com/Safe-Support-Chat/ocrcc-bot.git
|
git clone https://github.com/nomadic-labs/safesupport-bot.git
|
||||||
```
|
```
|
||||||
|
|
||||||
Install dependencies
|
Install dependencies
|
||||||
@ -39,14 +48,9 @@ cd safesupport-bot
|
|||||||
yarn
|
yarn
|
||||||
```
|
```
|
||||||
|
|
||||||
Copy the sample config file and add in the missing values.
|
Copy the sample `.env` file and add in your own variables
|
||||||
```
|
```
|
||||||
cp sample.config.json config.json
|
cp .env.sample .env
|
||||||
```
|
|
||||||
|
|
||||||
Pull in the user-defined settings (if there are any).
|
|
||||||
```
|
|
||||||
yarn setup
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Start the local server
|
Start the local server
|
||||||
|
363
dist/bot.js
vendored
363
dist/bot.js
vendored
@ -27,18 +27,16 @@ var _encryptAttachment = _interopRequireDefault(require("./encrypt-attachment"))
|
|||||||
|
|
||||||
global.Olm = require("olm");
|
global.Olm = require("olm");
|
||||||
const BOT_SIGNAL_END_CHAT = 'END_CHAT';
|
const BOT_SIGNAL_END_CHAT = 'END_CHAT';
|
||||||
const BOT_SIGNAL_CHAT_OFFLINE = 'CHAT_OFFLINE';
|
|
||||||
|
|
||||||
class OcrccBot {
|
class OcrccBot {
|
||||||
constructor(config) {
|
constructor(botConfig) {
|
||||||
this.config = config;
|
this.config = botConfig;
|
||||||
this.client = matrix.createClient(this.config.matrixServerUrl);
|
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
|
||||||
this.joinedRooms = [];
|
this.joinedRooms = [];
|
||||||
this.inactivityTimers = {};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
createLocalStorage() {
|
createLocalStorage() {
|
||||||
const storageLoc = `matrix-chatbot-${this.config.botUsername}`;
|
const storageLoc = `matrix-chatbot-${this.config.BOT_USERNAME}`;
|
||||||
const dir = path.resolve(path.join(os.homedir(), ".local-storage"));
|
const dir = path.resolve(path.join(os.homedir(), ".local-storage"));
|
||||||
|
|
||||||
if (!fs.existsSync(dir)) {
|
if (!fs.existsSync(dir)) {
|
||||||
@ -49,20 +47,20 @@ class OcrccBot {
|
|||||||
return new _nodeLocalstorage.LocalStorage(localStoragePath);
|
return new _nodeLocalstorage.LocalStorage(localStoragePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendTextMessage(roomId, msgText, showToUser = null) {
|
sendTextMessage(roomId, msgText, showToUser = null) {
|
||||||
const content = {
|
const content = {
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: msgText,
|
body: msgText,
|
||||||
showToUser: showToUser
|
showToUser: showToUser
|
||||||
};
|
};
|
||||||
await this.sendMessage(roomId, content);
|
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":
|
||||||
@ -112,9 +110,17 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inviteUserToRoom(roomId, member) {
|
||||||
|
try {
|
||||||
|
this.client.invite(roomId, member);
|
||||||
|
} catch (err) {
|
||||||
|
this.handleBotCrash(roomId, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
kickUserFromRoom(roomId, member) {
|
kickUserFromRoom(roomId, member) {
|
||||||
try {
|
try {
|
||||||
this.client.kick(roomId, member, this.config.kickReason);
|
this.client.kick(roomId, member, this.config.KICK_REASON);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.handleBotCrash(roomId, err);
|
this.handleBotCrash(roomId, err);
|
||||||
|
|
||||||
@ -122,50 +128,28 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async inviteFacilitatorIfOnline(roomId, memberId) {
|
|
||||||
const user = this.client.getUser(memberId);
|
|
||||||
|
|
||||||
if (user && user.presence !== "offline" && memberId !== this.config.botUserId) {
|
|
||||||
try {
|
|
||||||
this.client.invite(roomId, memberId);
|
|
||||||
|
|
||||||
_logger.default.log("info", `CHAT INVITATION SENT TO ${memberId} FOR ROOM ${roomId}`);
|
|
||||||
|
|
||||||
return memberId;
|
|
||||||
} catch (err) {
|
|
||||||
this.handleBotCrash(roomId, err);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async inviteFacilitators(roomId) {
|
async inviteFacilitators(roomId) {
|
||||||
|
this.localStorage.setItem(`${roomId}-waiting`, 'true');
|
||||||
|
let invitations = [];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
this.localStorage.setItem(`${roomId}-waiting`, 'true');
|
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
|
||||||
let invitations = [];
|
|
||||||
const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId);
|
|
||||||
const members = Object.keys(roomMembers["joined"]);
|
const members = Object.keys(roomMembers["joined"]);
|
||||||
|
members.forEach(memberId => {
|
||||||
|
const user = this.client.getUser(memberId);
|
||||||
|
|
||||||
for (const memberId of members) {
|
if (user && user.presence !== "offline" && memberId !== this.config.BOT_USERID) {
|
||||||
const invited = await this.inviteFacilitatorIfOnline(roomId, memberId);
|
invitations.push(memberId);
|
||||||
invitations.push(invited);
|
this.inviteUserToRoom(roomId, memberId);
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
|
||||||
if (invitations.filter(i => i).length > 0) {
|
if (invitations.length > 0) {
|
||||||
this.localStorage.setItem(`${roomId}-invitations`, invitations);
|
this.localStorage.setItem(`${roomId}-invitations`, invitations);
|
||||||
} else {
|
} else {
|
||||||
this.sendBotSignal(roomId, BOT_SIGNAL_CHAT_OFFLINE); // send notification to Support Chat Notifications room
|
_logger.default.log('info', "NO FACILITATORS ONLINE");
|
||||||
|
|
||||||
const currentDate = new Date();
|
this.sendNotice(roomId, "CHAT_OFFLINE");
|
||||||
const closedTime = currentDate.toLocaleTimeString();
|
|
||||||
const roomRef = roomId.split(':')[0];
|
|
||||||
const notification = `No facilitators were online, chat closed at ${closedTime} (room ID: ${roomRef})`;
|
|
||||||
|
|
||||||
_logger.default.log('info', `NO FACILITATORS ONLINE, CHAT CLOSED AT ${closedTime} (room ID: ${roomRef})`);
|
|
||||||
|
|
||||||
this.sendTextMessage(this.config.facilitatorRoomId, notification);
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.handleBotCrash(roomId, err);
|
this.handleBotCrash(roomId, err);
|
||||||
@ -175,9 +159,10 @@ 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.facilitatorRoomId);
|
|
||||||
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"]);
|
||||||
const facilitatorsIds = Object.keys(facilitatorsRoomMembers["joined"]);
|
const facilitatorsIds = Object.keys(facilitatorsRoomMembers["joined"]);
|
||||||
@ -196,27 +181,17 @@ class OcrccBot {
|
|||||||
|
|
||||||
handleBotCrash(roomId, error) {
|
handleBotCrash(roomId, error) {
|
||||||
if (roomId) {
|
if (roomId) {
|
||||||
this.sendTextMessage(roomId, this.config.botErrorMessage);
|
this.sendTextMessage(roomId, this.config.BOT_ERROR_MESSAGE);
|
||||||
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.sendTextMessage(this.config.facilitatorRoomId, `${this.config.botDisplayName} ran into an error: ${error}. Please verify that the chat service is working.`);
|
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, `The Help Bot 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(); // do nothing if there's no content
|
||||||
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.botUserId) {
|
|
||||||
this.setInactivityTimeout(roomId);
|
|
||||||
} // bot commands
|
} // bot commands
|
||||||
|
|
||||||
|
|
||||||
@ -225,7 +200,7 @@ class OcrccBot {
|
|||||||
} // write to transcript
|
} // write to transcript
|
||||||
|
|
||||||
|
|
||||||
if (this.config.captureTranscripts) {
|
if (this.config.CAPTURE_TRANSCRIPTS) {
|
||||||
return this.writeToTranscript(event);
|
return this.writeToTranscript(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -242,7 +217,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}. This message will not be added: ${content.body}`);
|
return _logger.default.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = `${sender} [${time}]: ${content.body}\n`;
|
const message = `${sender} [${time}]: ${content.body}\n`;
|
||||||
@ -261,9 +236,8 @@ class OcrccBot {
|
|||||||
}, {
|
}, {
|
||||||
keyword: 'delete transcript',
|
keyword: 'delete transcript',
|
||||||
function: (senderId, roomId) => {
|
function: (senderId, roomId) => {
|
||||||
this.deleteTranscript(senderId, roomId, true);
|
this.deleteTranscript(senderId, roomId);
|
||||||
} // delete transcript and send confirmation message
|
}
|
||||||
|
|
||||||
}, {
|
}, {
|
||||||
keyword: 'say',
|
keyword: 'say',
|
||||||
function: (senderId, roomId, message) => {
|
function: (senderId, roomId, message) => {
|
||||||
@ -276,12 +250,6 @@ class OcrccBot {
|
|||||||
const message = responses[Math.floor(Math.random() * responses.length)];
|
const message = responses[Math.floor(Math.random() * responses.length)];
|
||||||
this.sendTextMessage(roomId, message, senderId);
|
this.sendTextMessage(roomId, message, senderId);
|
||||||
}
|
}
|
||||||
}, {
|
|
||||||
keyword: 'bug',
|
|
||||||
function: (senderId, roomId) => {
|
|
||||||
const message = `Please report the issue at ${this.config.bugReportUrl}`;
|
|
||||||
this.sendTextMessage(roomId, message, senderId);
|
|
||||||
}
|
|
||||||
}];
|
}];
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@ -302,7 +270,7 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async leaveEmptyRooms() {
|
async leaveEmptyRooms(senderId) {
|
||||||
try {
|
try {
|
||||||
const roomData = await this.client.getJoinedRooms();
|
const roomData = await this.client.getJoinedRooms();
|
||||||
const joinedRoomsIds = roomData["joined_rooms"];
|
const joinedRoomsIds = roomData["joined_rooms"];
|
||||||
@ -311,16 +279,16 @@ class OcrccBot {
|
|||||||
|
|
||||||
if (room && room.getJoinedMemberCount() === 1) {
|
if (room && room.getJoinedMemberCount() === 1) {
|
||||||
try {
|
try {
|
||||||
await this.client.leave(roomId);
|
_logger.default.log('info', "LEAVING EMPTY ROOM => " + roomId);
|
||||||
|
|
||||||
_logger.default.log('info', `LEAVING EMPTY ROOM => ${roomId}`);
|
await this.client.leave(roomId);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
_logger.default.log('error', `ERROR LEAVING ROOM ${roomId} => ${err}`);
|
_logger.default.log('error', "ERROR LEAVING EMPTY ROOM => " + err);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
_logger.default.log("error", `ERROR LEAVING EMPTY ROOMS: ${err}`);
|
_logger.default.log("error", `ERROR GETTING JOINED ROOMS: ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -329,7 +297,7 @@ class OcrccBot {
|
|||||||
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
|
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
|
||||||
|
|
||||||
if (!transcriptFile) {
|
if (!transcriptFile) {
|
||||||
this.sendTextMessage(roomId, "Cannot send transcript, there is no transcript for this chat.", senderId);
|
this.sendTextMessage(roomId, "There is no transcript for this chat.", senderId);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.client.isRoomEncrypted(roomId)) {
|
if (this.client.isRoomEncrypted(roomId)) {
|
||||||
@ -388,11 +356,11 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteTranscript(senderId, roomId, sendConfirmation = false) {
|
deleteTranscript(senderId, roomId) {
|
||||||
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
|
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
|
||||||
|
|
||||||
if (!transcriptFile) {
|
if (!transcriptFile) {
|
||||||
return this.sendTextMessage(roomId, "Cannot delete transcript, there is no transcript for this chat.", senderId);
|
return this.sendTextMessage(roomId, "There is no transcript for this chat.", senderId);
|
||||||
}
|
}
|
||||||
|
|
||||||
fs.unlink(transcriptFile, err => {
|
fs.unlink(transcriptFile, err => {
|
||||||
@ -404,13 +372,11 @@ 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);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (sendConfirmation) {
|
this.localStorage.removeItem(`${roomId}-transcript`);
|
||||||
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.localStorage.removeItem(`${roomId}-transcript`);
|
this.sendTextMessage(roomId, `The transcript file has been deleted.`, senderId);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -428,12 +394,12 @@ class OcrccBot {
|
|||||||
const auth = {
|
const auth = {
|
||||||
session: err.data.session,
|
session: err.data.session,
|
||||||
type: "m.login.password",
|
type: "m.login.password",
|
||||||
user: this.config.botUserId,
|
user: this.config.BOT_USERID,
|
||||||
identifier: {
|
identifier: {
|
||||||
type: "m.id.user",
|
type: "m.id.user",
|
||||||
user: this.config.botUserId
|
user: this.config.BOT_USERID
|
||||||
},
|
},
|
||||||
password: this.config.botPassword
|
password: this.config.BOT_PASSWORD
|
||||||
};
|
};
|
||||||
await this.client.deleteMultipleDevices(oldDevices, auth);
|
await this.client.deleteMultipleDevices(oldDevices, auth);
|
||||||
|
|
||||||
@ -451,7 +417,7 @@ class OcrccBot {
|
|||||||
async setMembershipListeners() {
|
async setMembershipListeners() {
|
||||||
// Automatically accept all room invitations
|
// Automatically accept all room invitations
|
||||||
this.client.on("RoomMember.membership", async (event, member) => {
|
this.client.on("RoomMember.membership", async (event, member) => {
|
||||||
if (member.membership === "invite" && member.userId === this.config.botUserId && !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 roomData = await this.client.getJoinedRooms();
|
||||||
const joinedRooms = roomData["joined_rooms"];
|
const joinedRooms = roomData["joined_rooms"];
|
||||||
@ -466,127 +432,110 @@ class OcrccBot {
|
|||||||
const chatTime = inviteDate.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.facilitatorRoomId, 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (member.membership === "join" && member.userId !== this.config.botUserId && 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.facilitatorRoomId);
|
const members = Object.keys(roomMembers["joined"]);
|
||||||
const members = Object.keys(roomMembers["joined"]);
|
const isFacilitator = members.includes(member.userId);
|
||||||
const isFacilitator = members.includes(member.userId);
|
|
||||||
|
|
||||||
if (isFacilitator) {
|
if (isFacilitator) {
|
||||||
// made facilitator a moderator in the room
|
// 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: () => {
|
||||||
return "m.room.power_levels";
|
return "m.room.power_levels";
|
||||||
},
|
},
|
||||||
getContent: () => {
|
getContent: () => {
|
||||||
return {
|
return {
|
||||||
users: {
|
users: {
|
||||||
[this.config.botUserId]: 100,
|
[this.config.BOT_USERID]: 100,
|
||||||
[member.userId]: 50
|
[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.facilitatorRoomId, 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.captureTranscripts) {
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
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.botUserId) {
|
if (member.membership === "leave" && member.userId !== this.config.BOT_USERID) {
|
||||||
// notify room if the facilitator has left
|
// ensure bot is still in the room
|
||||||
try {
|
const roomData = await this.client.getJoinedRooms();
|
||||||
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`);
|
const joinedRooms = roomData["joined_rooms"];
|
||||||
|
const isBotInRoom = joinedRooms.includes(member.roomId);
|
||||||
if (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.facilitatorRoomId, notification);
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
_logger.default.log("error", `ERROR NOTIFYING THAT FACLITATOR HAS LEFT THE ROOM ==> ${err}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const room = this.client.getRoom(member.roomId);
|
const room = this.client.getRoom(member.roomId);
|
||||||
if (!room) return;
|
if (!room) return; // notify room if the facilitator has left
|
||||||
const roomMembers = await room.getJoinedMembers(); // array
|
|
||||||
// leave if there is nobody in the room
|
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
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const memberCount = roomMembers.length;
|
const memberCount = room.getJoinedMemberCount();
|
||||||
const isBotInRoom = Boolean(roomMembers.find(member => member.userId === this.config.botUserId));
|
|
||||||
|
|
||||||
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`);
|
||||||
this.localStorage.removeItem(`${member.roomId}-waiting`);
|
return this.client.leave(member.roomId);
|
||||||
return await this.client.leave(member.roomId);
|
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return _logger.default.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
|
_logger.default.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
|
||||||
} // send signal to close the chat if there are no facilitators in the room
|
} // send signal to close the chat if there are no facilitators in the room
|
||||||
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId); // object
|
const roomMembers = await room.getJoinedMembers();
|
||||||
|
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
|
||||||
const facilitators = facilitatorRoomMembers['joined'];
|
const facilitators = facilitatorRoomMembers['joined'];
|
||||||
let facilitatorInRoom = false;
|
let facilitatorInRoom = false;
|
||||||
roomMembers.forEach(member => {
|
roomMembers.forEach(member => {
|
||||||
if (member.userId !== this.config.botUserId && Boolean(facilitators[member.userId])) {
|
if (member.userId !== this.config.BOT_USERID && Boolean(facilitators[member.userId])) {
|
||||||
facilitatorInRoom = true;
|
facilitatorInRoom = true;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!facilitatorInRoom) {
|
if (!facilitatorInRoom) {
|
||||||
_logger.default.log("info", `NO FACILITATORS LEFT, SENDING SIGNAL TO END CHAT`);
|
|
||||||
|
|
||||||
this.sendBotSignal(member.roomId, BOT_SIGNAL_END_CHAT);
|
this.sendBotSignal(member.roomId, BOT_SIGNAL_END_CHAT);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@ -596,42 +545,6 @@ class OcrccBot {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
setTimeoutforFacilitator(roomId) {
|
|
||||||
setTimeout(async () => {
|
|
||||||
const stillWaiting = this.localStorage.getItem(`${roomId}-waiting`);
|
|
||||||
|
|
||||||
if (stillWaiting) {
|
|
||||||
await this.sendTextMessage(roomId, this.config.chatNotAvailableMessage);
|
|
||||||
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT); // send notification to Support Chat Notifications room
|
|
||||||
|
|
||||||
const currentDate = new Date();
|
|
||||||
const closedTime = currentDate.toLocaleTimeString();
|
|
||||||
const roomRef = roomId.split(':')[0];
|
|
||||||
const notification = `No facilitators joined the chat within the maximum wait time, chat closed at ${closedTime} (room ID: ${roomRef})`;
|
|
||||||
this.sendTextMessage(this.config.facilitatorRoomId, notification);
|
|
||||||
|
|
||||||
_logger.default.log("info", `NO FACILITATORS JOINED THE CHAT WITHIN THE MAXIMUM WAIT TIME, CHAT CLOSED AT ${closedTime} (room ID: ${roomRef})`);
|
|
||||||
}
|
|
||||||
}, this.config.maxWaitTime * 1000); // convert seconds to milliseconds
|
|
||||||
}
|
|
||||||
|
|
||||||
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.config.chatInactiveMessage);
|
|
||||||
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT);
|
|
||||||
}, this.config.maxInactiveTime * 1000); // convert seconds to milliseconds
|
|
||||||
|
|
||||||
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) => {
|
||||||
@ -651,36 +564,43 @@ 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) {
|
async sendBotSignal(roomId, signal, args) {
|
||||||
let content = {
|
let content = {
|
||||||
signal: signal,
|
signal: signal,
|
||||||
args: args
|
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() {
|
async start() {
|
||||||
|
const localStorage = this.createLocalStorage();
|
||||||
|
this.localStorage = localStorage;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const localStorage = this.createLocalStorage();
|
|
||||||
this.localStorage = localStorage;
|
|
||||||
const auth = {
|
const auth = {
|
||||||
user: this.config.botUsername,
|
user: this.config.BOT_USERNAME,
|
||||||
password: this.config.botPassword,
|
password: this.config.BOT_PASSWORD,
|
||||||
initial_device_display_name: this.config.botDisplayName
|
initial_device_display_name: this.config.BOT_DISPLAY_NAME
|
||||||
};
|
};
|
||||||
const account = await this.client.login("m.login.password", auth);
|
const account = await this.client.login("m.login.password", auth);
|
||||||
|
|
||||||
_logger.default.log("info", `ACCOUNT ==> ${JSON.stringify(account)}`);
|
_logger.default.log("info", `ACCOUNT ==> ${JSON.stringify(account)}`);
|
||||||
|
|
||||||
let opts = {
|
let opts = {
|
||||||
baseUrl: this.config.matrixServerUrl,
|
baseUrl: this.config.MATRIX_SERVER_URL,
|
||||||
accessToken: account.access_token,
|
accessToken: account.access_token,
|
||||||
userId: this.config.botUserId,
|
userId: this.config.BOT_USERID,
|
||||||
deviceId: account.device_id,
|
deviceId: account.device_id,
|
||||||
sessionStore: new matrix.WebStorageSessionStore(localStorage)
|
sessionStore: new matrix.WebStorageSessionStore(localStorage)
|
||||||
};
|
};
|
||||||
@ -694,7 +614,6 @@ 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,8 +103,6 @@ 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);
|
||||||
@ -278,16 +276,4 @@ 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
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
});
|
39
dist/index.js
vendored
39
dist/index.js
vendored
@ -2,14 +2,37 @@
|
|||||||
|
|
||||||
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
||||||
|
|
||||||
var _config = _interopRequireDefault(require("../config.json"));
|
|
||||||
|
|
||||||
var _bot = _interopRequireDefault(require("./bot"));
|
var _bot = _interopRequireDefault(require("./bot"));
|
||||||
|
|
||||||
const bot = new _bot.default(_config.default);
|
require('dotenv').config();
|
||||||
|
|
||||||
try {
|
const ENCRYPTION_CONFIG = {
|
||||||
bot.start();
|
algorithm: "m.megolm.v1.aes-sha2"
|
||||||
} catch (err) {
|
};
|
||||||
console.log("Unable to start bot", err);
|
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,
|
||||||
|
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,
|
||||||
|
CAPTURE_TRANSCRIPTS
|
||||||
|
};
|
||||||
|
const bot = new _bot.default(botConfig);
|
||||||
|
bot.start();
|
54
dist/setup.js
vendored
54
dist/setup.js
vendored
@ -1,54 +0,0 @@
|
|||||||
"use strict";
|
|
||||||
|
|
||||||
const fs = require('fs');
|
|
||||||
|
|
||||||
const fetch = require('node-fetch');
|
|
||||||
|
|
||||||
const config = require('../config.json');
|
|
||||||
|
|
||||||
const getSettings = async () => {
|
|
||||||
try {
|
|
||||||
const url = `${config.settingsEndpoint}?homeserver=${encodeURIComponent(config.matrixServerUrl)}`;
|
|
||||||
|
|
||||||
if (!config.matrixServerUrl) {
|
|
||||||
throw new Error("The matrix server url is not provided");
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`Fetching settings for ${config.matrixServerUrl}`);
|
|
||||||
const res = await fetch(url);
|
|
||||||
const data = await res.json();
|
|
||||||
const {
|
|
||||||
fields,
|
|
||||||
schedule = []
|
|
||||||
} = data;
|
|
||||||
return Object.entries(fields).reduce((settingsObj, [k, v]) => {
|
|
||||||
const [scope, key] = k.split('_');
|
|
||||||
|
|
||||||
if (scope === 'platform') {
|
|
||||||
settingsObj[key] = v;
|
|
||||||
}
|
|
||||||
|
|
||||||
return settingsObj;
|
|
||||||
}, {});
|
|
||||||
} catch (err) {
|
|
||||||
console.log("Error fetching settings", err);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const writeConfig = async () => {
|
|
||||||
const settings = await getSettings();
|
|
||||||
|
|
||||||
if (!settings) {
|
|
||||||
return console.log('No settings to update');
|
|
||||||
}
|
|
||||||
|
|
||||||
const updatedSettings = Object.assign(config, settings);
|
|
||||||
fs.writeFile('config.json', JSON.stringify(updatedSettings, null, 2), function (err) {
|
|
||||||
if (err) return console.log("Error updating settings", err);
|
|
||||||
console.log(`Updated settings to config.json`);
|
|
||||||
console.log(updatedSettings);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
writeConfig();
|
|
@ -1,12 +1,11 @@
|
|||||||
{
|
{
|
||||||
"name": "private-safesupport-bot",
|
"name": "private-safesupport-bot",
|
||||||
"version": "3.1.0",
|
"version": "1.2.0",
|
||||||
"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": {
|
||||||
"develop": "nodemon --exec babel-node src/index.js",
|
"develop": "nodemon --exec babel-node src/index.js",
|
||||||
"build": "babel src -d dist",
|
"build": "babel src -d dist",
|
||||||
"setup": "node src/setup.js",
|
|
||||||
"start": "yarn build && node dist/index.js",
|
"start": "yarn build && node dist/index.js",
|
||||||
"test": "jest"
|
"test": "jest"
|
||||||
},
|
},
|
||||||
@ -15,7 +14,6 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"dotenv": "^8.2.0",
|
"dotenv": "^8.2.0",
|
||||||
"matrix-js-sdk": "^6.2.1",
|
"matrix-js-sdk": "^6.2.1",
|
||||||
"node-fetch": "^2.6.1",
|
|
||||||
"node-localstorage": "^2.1.5",
|
"node-localstorage": "^2.1.5",
|
||||||
"node-webcrypto-ossl": "^2.1.0",
|
"node-webcrypto-ossl": "^2.1.0",
|
||||||
"olm": "https://packages.matrix.org/npm/olm/olm-3.1.4.tgz",
|
"olm": "https://packages.matrix.org/npm/olm/olm-3.1.4.tgz",
|
||||||
|
@ -1,16 +0,0 @@
|
|||||||
{
|
|
||||||
"matrixServerUrl": "",
|
|
||||||
"settingsEndpoint": "",
|
|
||||||
"facilitatorRoomId": "",
|
|
||||||
"kickReason": "A facilitator has already joined this chat.",
|
|
||||||
"botErrorMessage": "Something went wrong on our end, please restart the chat and try again.",
|
|
||||||
"botUserId": "",
|
|
||||||
"botUsername": "",
|
|
||||||
"botPassword": "",
|
|
||||||
"botDisplayName": "Help Bot",
|
|
||||||
"captureTranscripts": true,
|
|
||||||
"chatNotAvailableMessage": "The support chat is not available right now.",
|
|
||||||
"chatInactiveMessage": "This chat has been closed due to inactivity.",
|
|
||||||
"maxWaitTime": 180,
|
|
||||||
"maxInactiveTime": 3600
|
|
||||||
}
|
|
245
src/bot.js
245
src/bot.js
@ -12,18 +12,18 @@ import logger from "./logger";
|
|||||||
import encrypt from "./encrypt-attachment";
|
import encrypt from "./encrypt-attachment";
|
||||||
|
|
||||||
const BOT_SIGNAL_END_CHAT = 'END_CHAT'
|
const BOT_SIGNAL_END_CHAT = 'END_CHAT'
|
||||||
const BOT_SIGNAL_CHAT_OFFLINE = 'CHAT_OFFLINE'
|
|
||||||
|
|
||||||
class OcrccBot {
|
class OcrccBot {
|
||||||
constructor(config) {
|
constructor(botConfig) {
|
||||||
this.config = config
|
this.config = botConfig
|
||||||
this.client = matrix.createClient(this.config.matrixServerUrl);
|
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
|
||||||
this.joinedRooms = [];
|
this.joinedRooms = [];
|
||||||
this.inactivityTimers = {};
|
this.inactivityTimers = {};
|
||||||
}
|
}
|
||||||
|
|
||||||
createLocalStorage() {
|
createLocalStorage() {
|
||||||
const storageLoc = `matrix-chatbot-${this.config.botUsername}`;
|
const storageLoc = `matrix-chatbot-${this.config.BOT_USERNAME}`;
|
||||||
const dir = path.resolve(path.join(os.homedir(), ".local-storage"));
|
const dir = path.resolve(path.join(os.homedir(), ".local-storage"));
|
||||||
if (!fs.existsSync(dir)) {
|
if (!fs.existsSync(dir)) {
|
||||||
fs.mkdirSync(dir);
|
fs.mkdirSync(dir);
|
||||||
@ -32,20 +32,21 @@ class OcrccBot {
|
|||||||
return new LocalStorage(localStoragePath);
|
return new LocalStorage(localStoragePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendTextMessage(roomId, msgText, showToUser = null) {
|
sendTextMessage(roomId, msgText, showToUser = null) {
|
||||||
const content = {
|
const content = {
|
||||||
msgtype: "m.text",
|
msgtype: "m.text",
|
||||||
body: msgText,
|
body: msgText,
|
||||||
showToUser: showToUser
|
showToUser: showToUser
|
||||||
};
|
};
|
||||||
|
|
||||||
await this.sendMessage(roomId, content);
|
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":
|
||||||
@ -90,59 +91,48 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inviteUserToRoom(roomId, member) {
|
||||||
|
try {
|
||||||
|
this.client.invite(roomId, member)
|
||||||
|
} catch(err) {
|
||||||
|
this.handleBotCrash(roomId, err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
kickUserFromRoom(roomId, member) {
|
kickUserFromRoom(roomId, member) {
|
||||||
try {
|
try {
|
||||||
this.client.kick(roomId, member, this.config.kickReason)
|
this.client.kick(roomId, member, this.config.KICK_REASON)
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
this.handleBotCrash(roomId, err);
|
this.handleBotCrash(roomId, err);
|
||||||
logger.log("error", `ERROR KICKING OUT MEMBER: ${err}`);
|
logger.log("error", `ERROR KICKING OUT MEMBER: ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async inviteFacilitatorIfOnline(roomId, memberId) {
|
|
||||||
const user = this.client.getUser(memberId);
|
|
||||||
if (
|
|
||||||
user &&
|
|
||||||
(user.presence !== "offline") &&
|
|
||||||
memberId !== this.config.botUserId
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
this.client.invite(roomId, memberId)
|
|
||||||
logger.log("info", `CHAT INVITATION SENT TO ${memberId} FOR ROOM ${roomId}`)
|
|
||||||
return memberId
|
|
||||||
} catch(err) {
|
|
||||||
this.handleBotCrash(roomId, err);
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async inviteFacilitators(roomId) {
|
async inviteFacilitators(roomId) {
|
||||||
|
this.localStorage.setItem(`${roomId}-waiting`, 'true')
|
||||||
|
let invitations = []
|
||||||
|
|
||||||
try {
|
try {
|
||||||
this.localStorage.setItem(`${roomId}-waiting`, 'true')
|
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID)
|
||||||
let invitations = []
|
|
||||||
const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId)
|
|
||||||
const members = Object.keys(roomMembers["joined"]);
|
const members = Object.keys(roomMembers["joined"]);
|
||||||
|
|
||||||
for (const memberId of members) {
|
members.forEach(memberId => {
|
||||||
const invited = await this.inviteFacilitatorIfOnline(roomId, memberId)
|
const user = this.client.getUser(memberId);
|
||||||
invitations.push(invited)
|
if (
|
||||||
}
|
user &&
|
||||||
|
(user.presence !== "offline") &&
|
||||||
|
memberId !== this.config.BOT_USERID
|
||||||
|
) {
|
||||||
|
invitations.push(memberId)
|
||||||
|
this.inviteUserToRoom(roomId, memberId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
if (invitations.filter(i => i).length > 0) {
|
if (invitations.length > 0) {
|
||||||
this.localStorage.setItem(`${roomId}-invitations`, invitations)
|
this.localStorage.setItem(`${roomId}-invitations`, invitations)
|
||||||
} else {
|
} else {
|
||||||
this.sendBotSignal(roomId, BOT_SIGNAL_CHAT_OFFLINE)
|
logger.log('info', "NO FACILITATORS ONLINE")
|
||||||
|
this.sendNotice(roomId, "CHAT_OFFLINE")
|
||||||
// send notification to Support Chat Notifications room
|
|
||||||
const currentDate = new Date()
|
|
||||||
const closedTime = currentDate.toLocaleTimeString()
|
|
||||||
const roomRef = roomId.split(':')[0]
|
|
||||||
const notification = `No facilitators were online, chat closed at ${closedTime} (room ID: ${roomRef})`
|
|
||||||
logger.log('info', `NO FACILITATORS ONLINE, CHAT CLOSED AT ${closedTime} (room ID: ${roomRef})`)
|
|
||||||
this.sendTextMessage(this.config.facilitatorRoomId, notification);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
@ -153,9 +143,10 @@ 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.facilitatorRoomId)
|
|
||||||
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"]);
|
||||||
@ -177,13 +168,12 @@ class OcrccBot {
|
|||||||
|
|
||||||
handleBotCrash(roomId, error) {
|
handleBotCrash(roomId, error) {
|
||||||
if (roomId) {
|
if (roomId) {
|
||||||
this.sendTextMessage(roomId, this.config.botErrorMessage);
|
this.sendTextMessage(roomId, this.config.BOT_ERROR_MESSAGE);
|
||||||
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.sendTextMessage(
|
this.sendTextMessage(
|
||||||
this.config.facilitatorRoomId,
|
this.config.FACILITATOR_ROOM_ID,
|
||||||
`${this.config.botDisplayName} ran into an error: ${error}. Please verify that the chat service is working.`
|
`The Help Bot ran into an error: ${error}. Please verify that the chat service is working.`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -199,7 +189,7 @@ class OcrccBot {
|
|||||||
|
|
||||||
// if it's a chat message and the facilitator has joined, reset the inactivity timeout
|
// if it's a chat message and the facilitator has joined, reset the inactivity timeout
|
||||||
const facilitatorId = this.localStorage.getItem(`${roomId}-facilitator`)
|
const facilitatorId = this.localStorage.getItem(`${roomId}-facilitator`)
|
||||||
if (Boolean(facilitatorId) && sender !== this.config.botUserId) {
|
if (Boolean(facilitatorId) && sender !== this.config.BOT_USERID) {
|
||||||
this.setInactivityTimeout(roomId)
|
this.setInactivityTimeout(roomId)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -209,7 +199,7 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// write to transcript
|
// write to transcript
|
||||||
if (this.config.captureTranscripts) {
|
if (this.config.CAPTURE_TRANSCRIPTS) {
|
||||||
return this.writeToTranscript(event);
|
return this.writeToTranscript(event);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -226,7 +216,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}. This message will not be added: ${content.body}`);
|
return logger.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const message = `${sender} [${time}]: ${content.body}\n`;
|
const message = `${sender} [${time}]: ${content.body}\n`;
|
||||||
@ -245,7 +235,7 @@ class OcrccBot {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
keyword: 'delete transcript',
|
keyword: 'delete transcript',
|
||||||
function: (senderId, roomId) => { this.deleteTranscript(senderId, roomId, true) } // delete transcript and send confirmation message
|
function: (senderId, roomId) => { this.deleteTranscript(senderId, roomId) }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
keyword: 'say',
|
keyword: 'say',
|
||||||
@ -266,13 +256,6 @@ class OcrccBot {
|
|||||||
const message = responses[Math.floor(Math.random() * responses.length)];
|
const message = responses[Math.floor(Math.random() * responses.length)];
|
||||||
this.sendTextMessage(roomId, message, senderId);
|
this.sendTextMessage(roomId, message, senderId);
|
||||||
}
|
}
|
||||||
},
|
|
||||||
{
|
|
||||||
keyword: 'bug',
|
|
||||||
function: (senderId, roomId) => {
|
|
||||||
const message = `Please report the issue at ${this.config.bugReportUrl}`
|
|
||||||
this.sendTextMessage(roomId, message, senderId);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
try {
|
try {
|
||||||
@ -297,7 +280,7 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async leaveEmptyRooms() {
|
async leaveEmptyRooms(senderId) {
|
||||||
try {
|
try {
|
||||||
const roomData = await this.client.getJoinedRooms()
|
const roomData = await this.client.getJoinedRooms()
|
||||||
const joinedRoomsIds = roomData["joined_rooms"]
|
const joinedRoomsIds = roomData["joined_rooms"]
|
||||||
@ -305,15 +288,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 ROOM ${roomId} => ${err}`)
|
logger.log('error', "ERROR LEAVING EMPTY ROOM => " + err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
logger.log("error", `ERROR LEAVING EMPTY ROOMS: ${err}`);
|
logger.log("error", `ERROR GETTING JOINED ROOMS: ${err}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -324,7 +307,7 @@ class OcrccBot {
|
|||||||
if (!transcriptFile) {
|
if (!transcriptFile) {
|
||||||
this.sendTextMessage(
|
this.sendTextMessage(
|
||||||
roomId,
|
roomId,
|
||||||
"Cannot send transcript, there is no transcript for this chat.",
|
"There is no transcript for this chat.",
|
||||||
senderId
|
senderId
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -387,13 +370,13 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
deleteTranscript(senderId, roomId, sendConfirmation=false) {
|
deleteTranscript(senderId, roomId) {
|
||||||
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,
|
||||||
"Cannot delete transcript, there is no transcript for this chat.",
|
"There is no transcript for this chat.",
|
||||||
senderId
|
senderId
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@ -409,17 +392,13 @@ class OcrccBot {
|
|||||||
senderId
|
senderId
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (sendConfirmation) {
|
|
||||||
this.sendTextMessage(
|
|
||||||
roomId,
|
|
||||||
`The transcript file has been deleted.`,
|
|
||||||
senderId
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.log('info', "DELETED TRANSCRIPT FILE => " + transcriptFile)
|
|
||||||
this.localStorage.removeItem(`${roomId}-transcript`)
|
this.localStorage.removeItem(`${roomId}-transcript`)
|
||||||
|
logger.log('info', "DELETED TRANSCRIPT FILE => " + transcriptFile)
|
||||||
|
this.sendTextMessage(
|
||||||
|
roomId,
|
||||||
|
`The transcript file has been deleted.`,
|
||||||
|
senderId
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -436,9 +415,9 @@ class OcrccBot {
|
|||||||
const auth = {
|
const auth = {
|
||||||
session: err.data.session,
|
session: err.data.session,
|
||||||
type: "m.login.password",
|
type: "m.login.password",
|
||||||
user: this.config.botUserId,
|
user: this.config.BOT_USERID,
|
||||||
identifier: { type: "m.id.user", user: this.config.botUserId },
|
identifier: { type: "m.id.user", user: this.config.BOT_USERID },
|
||||||
password: this.config.botPassword
|
password: this.config.BOT_PASSWORD
|
||||||
};
|
};
|
||||||
|
|
||||||
await this.client.deleteMultipleDevices(oldDevices, auth)
|
await this.client.deleteMultipleDevices(oldDevices, auth)
|
||||||
@ -457,7 +436,7 @@ class OcrccBot {
|
|||||||
this.client.on("RoomMember.membership", async (event, member) => {
|
this.client.on("RoomMember.membership", async (event, member) => {
|
||||||
if (
|
if (
|
||||||
member.membership === "invite" &&
|
member.membership === "invite" &&
|
||||||
member.userId === this.config.botUserId &&
|
member.userId === this.config.BOT_USERID &&
|
||||||
!this.joinedRooms.includes(member.roomId)
|
!this.joinedRooms.includes(member.roomId)
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
@ -471,7 +450,7 @@ class OcrccBot {
|
|||||||
const chatTime = inviteDate.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.facilitatorRoomId, notification);
|
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification);
|
||||||
this.inviteFacilitators(room.roomId)
|
this.inviteFacilitators(room.roomId)
|
||||||
this.setTimeoutforFacilitator(room.roomId)
|
this.setTimeoutforFacilitator(room.roomId)
|
||||||
}
|
}
|
||||||
@ -482,12 +461,12 @@ class OcrccBot {
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
member.membership === "join" &&
|
member.membership === "join" &&
|
||||||
member.userId !== this.config.botUserId &&
|
member.userId !== this.config.BOT_USERID &&
|
||||||
this.localStorage.getItem(`${member.roomId}-waiting`)
|
this.localStorage.getItem(`${member.roomId}-waiting`)
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
// make sure it's a facilitator joining
|
// make sure it's a facilitator joining
|
||||||
const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId)
|
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID)
|
||||||
const members = Object.keys(roomMembers["joined"]);
|
const members = Object.keys(roomMembers["joined"]);
|
||||||
const isFacilitator = members.includes(member.userId)
|
const isFacilitator = members.includes(member.userId)
|
||||||
|
|
||||||
@ -501,7 +480,7 @@ class OcrccBot {
|
|||||||
getContent: () => {
|
getContent: () => {
|
||||||
return {
|
return {
|
||||||
users: {
|
users: {
|
||||||
[this.config.botUserId]: 100,
|
[this.config.BOT_USERID]: 100,
|
||||||
[member.userId]: 50
|
[member.userId]: 50
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@ -514,7 +493,7 @@ class OcrccBot {
|
|||||||
const chatTime = currentDate.toLocaleTimeString()
|
const chatTime = currentDate.toLocaleTimeString()
|
||||||
const roomId = member.roomId.split(':')[0]
|
const roomId = member.roomId.split(':')[0]
|
||||||
const notification = `${member.name} joined the chat at ${chatTime} (room ID: ${roomId})`
|
const notification = `${member.name} joined the chat at ${chatTime} (room ID: ${roomId})`
|
||||||
this.sendTextMessage(this.config.facilitatorRoomId, notification);
|
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification);
|
||||||
|
|
||||||
// send notification to chat room
|
// send notification to chat room
|
||||||
this.sendTextMessage(
|
this.sendTextMessage(
|
||||||
@ -526,7 +505,7 @@ class OcrccBot {
|
|||||||
this.uninviteFacilitators(member.roomId);
|
this.uninviteFacilitators(member.roomId);
|
||||||
|
|
||||||
// set transcript file
|
// set transcript file
|
||||||
if (this.config.captureTranscripts) {
|
if (this.config.CAPTURE_TRANSCRIPTS) {
|
||||||
const currentDate = new Date();
|
const currentDate = new Date();
|
||||||
const dateOpts = {
|
const dateOpts = {
|
||||||
year: "numeric",
|
year: "numeric",
|
||||||
@ -549,62 +528,54 @@ class OcrccBot {
|
|||||||
|
|
||||||
if (
|
if (
|
||||||
member.membership === "leave" &&
|
member.membership === "leave" &&
|
||||||
member.userId !== this.config.botUserId
|
member.userId !== this.config.BOT_USERID
|
||||||
) {
|
) {
|
||||||
|
const room = this.client.getRoom(member.roomId)
|
||||||
|
if (!room) return;
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
// notify room if the facilitator has left
|
// notify room if the facilitator has left
|
||||||
try {
|
try {
|
||||||
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`)
|
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`)
|
||||||
if (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.facilitatorRoomId, notification);
|
|
||||||
}
|
}
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
logger.log("error", `ERROR NOTIFYING THAT FACLITATOR HAS LEFT THE ROOM ==> ${err}`);
|
logger.log("error", `ERROR NOTIFYING THAT FACLITATOR HAS LEFT THE ROOM ==> ${err}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const room = this.client.getRoom(member.roomId)
|
|
||||||
if (!room) return;
|
|
||||||
const roomMembers = await room.getJoinedMembers() // array
|
|
||||||
|
|
||||||
// leave if there is nobody in the room
|
// leave if there is nobody in the room
|
||||||
try {
|
try {
|
||||||
const memberCount = roomMembers.length
|
const memberCount = roomMembers.length
|
||||||
const isBotInRoom = Boolean(roomMembers.find(member => member.userId === this.config.botUserId))
|
|
||||||
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`)
|
||||||
this.localStorage.removeItem(`${member.roomId}-waiting`)
|
return this.client.leave(member.roomId)
|
||||||
return await this.client.leave(member.roomId)
|
|
||||||
}
|
}
|
||||||
} catch(err) {
|
} catch(err) {
|
||||||
return logger.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
|
logger.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// send signal to close the chat if there are no facilitators in the room
|
// send signal to close the chat if there are no facilitators in the room
|
||||||
try {
|
try {
|
||||||
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId) // object
|
|
||||||
const facilitators = facilitatorRoomMembers['joined']
|
const facilitators = facilitatorRoomMembers['joined']
|
||||||
let facilitatorInRoom = false;
|
let facilitatorInRoom = false;
|
||||||
|
|
||||||
roomMembers.forEach(member => {
|
roomMembers.forEach(member => {
|
||||||
if (member.userId !== this.config.botUserId && Boolean(facilitators[member.userId])) {
|
if (member.userId !== this.config.BOT_USERID && Boolean(facilitators[member.userId])) {
|
||||||
facilitatorInRoom = true
|
facilitatorInRoom = true
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
if (!facilitatorInRoom) {
|
if (!facilitatorInRoom) {
|
||||||
logger.log("info", `NO FACILITATORS LEFT, SENDING SIGNAL TO END CHAT`);
|
|
||||||
this.sendBotSignal(member.roomId, BOT_SIGNAL_END_CHAT)
|
this.sendBotSignal(member.roomId, BOT_SIGNAL_END_CHAT)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -616,24 +587,12 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
setTimeoutforFacilitator(roomId) {
|
setTimeoutforFacilitator(roomId) {
|
||||||
setTimeout(async() => {
|
setTimeout(() => {
|
||||||
const stillWaiting = this.localStorage.getItem(`${roomId}-waiting`)
|
const stillWaiting = this.localStorage.getItem(`${roomId}-waiting`)
|
||||||
if (stillWaiting) {
|
if (stillWaiting) {
|
||||||
await this.sendTextMessage(
|
|
||||||
roomId,
|
|
||||||
this.config.chatNotAvailableMessage
|
|
||||||
);
|
|
||||||
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
|
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
|
||||||
|
|
||||||
// send notification to Support Chat Notifications room
|
|
||||||
const currentDate = new Date()
|
|
||||||
const closedTime = currentDate.toLocaleTimeString()
|
|
||||||
const roomRef = roomId.split(':')[0]
|
|
||||||
const notification = `No facilitators joined the chat within the maximum wait time, chat closed at ${closedTime} (room ID: ${roomRef})`;
|
|
||||||
this.sendTextMessage(this.config.facilitatorRoomId, notification);
|
|
||||||
logger.log("info", `NO FACILITATORS JOINED THE CHAT WITHIN THE MAXIMUM WAIT TIME, CHAT CLOSED AT ${closedTime} (room ID: ${roomRef})`);
|
|
||||||
}
|
}
|
||||||
}, this.config.maxWaitTime * 1000) // convert seconds to milliseconds
|
}, this.config.MAX_WAIT_TIME)
|
||||||
}
|
}
|
||||||
|
|
||||||
setInactivityTimeout(roomId) {
|
setInactivityTimeout(roomId) {
|
||||||
@ -643,14 +602,13 @@ class OcrccBot {
|
|||||||
clearTimeout(oldTimeout);
|
clearTimeout(oldTimeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
const newTimeout = setTimeout(async() => {
|
const newTimeout = setTimeout(() => {
|
||||||
logger.log("info", `CHAT IS INACTIVE, SENDING SIGNAL TO END CHAT`);
|
this.sendTextMessage(
|
||||||
await this.sendTextMessage(
|
|
||||||
roomId,
|
roomId,
|
||||||
this.config.chatInactiveMessage
|
`This chat has been closed due to inactivity.`
|
||||||
);
|
);
|
||||||
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
|
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
|
||||||
}, this.config.maxInactiveTime * 1000) // convert seconds to milliseconds
|
}, this.config.MAX_INACTIVE)
|
||||||
|
|
||||||
this.inactivityTimers[roomId] = newTimeout;
|
this.inactivityTimers[roomId] = newTimeout;
|
||||||
}
|
}
|
||||||
@ -673,6 +631,18 @@ 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) {
|
async sendBotSignal (roomId, signal, args) {
|
||||||
let content = {
|
let content = {
|
||||||
signal: signal,
|
signal: signal,
|
||||||
@ -686,22 +656,22 @@ class OcrccBot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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.botUsername,
|
user: this.config.BOT_USERNAME,
|
||||||
password: this.config.botPassword,
|
password: this.config.BOT_PASSWORD,
|
||||||
initial_device_display_name: this.config.botDisplayName
|
initial_device_display_name: this.config.BOT_DISPLAY_NAME
|
||||||
}
|
}
|
||||||
const account = await this.client.login("m.login.password", auth)
|
const account = await this.client.login("m.login.password", auth)
|
||||||
logger.log("info", `ACCOUNT ==> ${JSON.stringify(account)}`);
|
logger.log("info", `ACCOUNT ==> ${JSON.stringify(account)}`);
|
||||||
|
|
||||||
let opts = {
|
let opts = {
|
||||||
baseUrl: this.config.matrixServerUrl,
|
baseUrl: this.config.MATRIX_SERVER_URL,
|
||||||
accessToken: account.access_token,
|
accessToken: account.access_token,
|
||||||
userId: this.config.botUserId,
|
userId: this.config.BOT_USERID,
|
||||||
deviceId: account.device_id,
|
deviceId: account.device_id,
|
||||||
sessionStore: new matrix.WebStorageSessionStore(localStorage)
|
sessionStore: new matrix.WebStorageSessionStore(localStorage)
|
||||||
};
|
};
|
||||||
@ -714,7 +684,6 @@ 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();
|
||||||
|
47
src/index.js
47
src/index.js
@ -1,9 +1,42 @@
|
|||||||
import config from '../config.json';
|
require('dotenv').config()
|
||||||
import OcrccBot from './bot';
|
|
||||||
|
|
||||||
const bot = new OcrccBot(config);
|
const ENCRYPTION_CONFIG = { algorithm: "m.megolm.v1.aes-sha2" };
|
||||||
try {
|
const KICK_REASON = "A facilitator has already joined this chat.";
|
||||||
bot.start();
|
const BOT_ERROR_MESSAGE =
|
||||||
} catch(err) {
|
"Something went wrong on our end, please restart the chat and try again.";
|
||||||
console.log("Unable to start bot", err)
|
const MAX_RETRIES = 3;
|
||||||
|
|
||||||
|
const {
|
||||||
|
MATRIX_SERVER_URL,
|
||||||
|
BOT_USERNAME,
|
||||||
|
BOT_USERID,
|
||||||
|
BOT_PASSWORD,
|
||||||
|
BOT_DISPLAY_NAME,
|
||||||
|
FACILITATOR_ROOM_ID,
|
||||||
|
CAPTURE_TRANSCRIPTS,
|
||||||
|
CHAT_NOT_AVAILABLE_MESSAGE,
|
||||||
|
MAX_WAIT_TIME,
|
||||||
|
MAX_INACTIVE,
|
||||||
|
} = 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,
|
||||||
|
CAPTURE_TRANSCRIPTS,
|
||||||
|
CHAT_NOT_AVAILABLE_MESSAGE,
|
||||||
|
MAX_WAIT_TIME,
|
||||||
|
MAX_INACTIVE,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
import OcrccBot from './bot'
|
||||||
|
|
||||||
|
const bot = new OcrccBot(botConfig);
|
||||||
|
bot.start();
|
||||||
|
50
src/setup.js
50
src/setup.js
@ -1,50 +0,0 @@
|
|||||||
const fs = require('fs');
|
|
||||||
const fetch = require('node-fetch');
|
|
||||||
const config = require('../config.json');
|
|
||||||
|
|
||||||
const getSettings = async () => {
|
|
||||||
try {
|
|
||||||
const url = `${config.settingsEndpoint}?homeserver=${encodeURIComponent(config.matrixServerUrl)}`;
|
|
||||||
|
|
||||||
if (!config.matrixServerUrl) {
|
|
||||||
throw new Error("The matrix server url is not provided")
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log(`Fetching settings for ${config.matrixServerUrl}`);
|
|
||||||
|
|
||||||
const res = await fetch(url);
|
|
||||||
const data = await res.json();
|
|
||||||
|
|
||||||
const { fields, schedule = [] } = data;
|
|
||||||
|
|
||||||
return Object.entries(fields).reduce(((settingsObj, [k,v]) => {
|
|
||||||
const [scope, key] = k.split('_');
|
|
||||||
|
|
||||||
if (scope === 'platform') {
|
|
||||||
settingsObj[key] = v;
|
|
||||||
}
|
|
||||||
|
|
||||||
return settingsObj
|
|
||||||
}), {});
|
|
||||||
} catch (err) {
|
|
||||||
console.log("Error fetching settings", err);
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const writeConfig = async () => {
|
|
||||||
const settings = await getSettings()
|
|
||||||
if (!settings) {
|
|
||||||
return console.log('No settings to update')
|
|
||||||
}
|
|
||||||
|
|
||||||
const updatedSettings = Object.assign(config, settings)
|
|
||||||
|
|
||||||
fs.writeFile('config.json', JSON.stringify(updatedSettings, null, 2), function (err) {
|
|
||||||
if (err) return console.log("Error updating settings", err);
|
|
||||||
console.log(`Updated settings to config.json`);
|
|
||||||
console.log(updatedSettings);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
writeConfig();
|
|
@ -3954,11 +3954,6 @@ node-environment-flags@^1.0.5:
|
|||||||
object.getownpropertydescriptors "^2.0.3"
|
object.getownpropertydescriptors "^2.0.3"
|
||||||
semver "^5.7.0"
|
semver "^5.7.0"
|
||||||
|
|
||||||
node-fetch@^2.6.1:
|
|
||||||
version "2.6.1"
|
|
||||||
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.1.tgz#045bd323631f76ed2e2b55573394416b639a0052"
|
|
||||||
integrity sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==
|
|
||||||
|
|
||||||
node-int64@^0.4.0:
|
node-int64@^0.4.0:
|
||||||
version "0.4.0"
|
version "0.4.0"
|
||||||
resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b"
|
resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b"
|
||||||
|
Loading…
Reference in New Issue
Block a user