Compare commits

...

23 Commits

Author SHA1 Message Date
Sharon Kennedy
139aa3a377 v3.1.0 2022-01-12 12:09:01 -05:00
Sharon Kennedy
f207e7a258 add bot command for bug reports 2022-01-12 12:05:19 -05:00
Sharon
135b9f079a
Update README.md 2021-12-20 14:24:18 -05:00
Sharon
46c2467368
Merge pull request #4 from nomadic-labs/use_admin_settings
Use admin settings
2020-12-01 13:26:02 -05:00
Sharon Kennedy
0ad65e9dcc remove encryption config 2020-12-01 13:25:06 -05:00
Sharon Kennedy
6c882a44cc latest build 2020-12-01 13:21:16 -05:00
Sharon Kennedy
666f2361c8 pull in user settings, fix race conditions on facilitator invitation, add more logging and notifications. 2020-12-01 13:20:13 -05:00
Sharon Kennedy
d3747cc654 fetch and use admin settings 2020-11-30 22:47:32 -05:00
Sharon Kennedy
687dfa84e9 2.0.2 2020-09-11 16:29:31 -04:00
Sharon Kennedy
b7da515969 Merge branch 'master' of github.com:nomadic-labs/ocrcc-bot 2020-09-11 16:29:08 -04:00
Sharon Kennedy
e2c291c040 change notice to signal 2020-09-11 16:12:01 -04:00
brent
87f2c5290f add timezone to dockerfile 2020-09-08 10:41:29 -04:00
Sharon Kennedy
4fdddc8c92 2.0.1 2020-09-07 12:00:16 -04:00
Sharon Kennedy
d53a5c5e26 change order of statements when handling member leaving to avoid sending close signal twice 2020-09-07 11:54:05 -04:00
brent
9772b3b1fd different strategy for python dependencies 2020-09-06 17:47:05 -04:00
brent
84fe91adbb new attempt at python install 2020-09-06 17:38:57 -04:00
brent
b6cd85eab0 removed parameters from python install 2020-09-06 17:33:12 -04:00
brent
209b3aaa45 removed sudo 2020-09-06 17:28:23 -04:00
edwardsbrentg
4912ce6f61
Merge pull request #3 from nomadic-labs/install-python-dockerfile
add python installation to dockerfile
2020-09-06 17:22:13 -04:00
brent
013ffa318f add python installation to dockerfile 2020-09-06 17:20:49 -04:00
Sharon Kennedy
ac2f953b90 2.0.0 2020-09-06 14:07:50 -04:00
Sharon Kennedy
a25c71a04a latest build 2020-09-06 14:07:44 -04:00
Sharon
836d4751ad
Merge pull request #2 from nomadic-labs/botsignal
Move timeouts to bot and use custom event to signal clients to close
2020-09-06 14:06:28 -04:00
14 changed files with 536 additions and 344 deletions

View File

@ -1,7 +0,0 @@
MATRIX_SERVER_URL=
BOT_DISPLAY_NAME=
BOT_USERNAME=
BOT_PASSWORD=
BOT_USERID=
FACILITATOR_ROOM_ID=
CAPTURE_TRANSCRIPTS

1
.gitignore vendored
View File

@ -3,3 +3,4 @@ node_modules
*.log
__mocks__/test_transcript.txt
transcripts/*.txt
config.json

View File

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

View File

@ -1,19 +1,10 @@
# 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/nomadic-labs/safesupport-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/Safe-Support-Chat/ocrcc-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?
* 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
@ -29,7 +20,7 @@ CAPTURE_TRANSCRIPTS=
### Bot commands
|Command|Response|
--- | ---
--- | ---
|`!bot hi`|Bot responds with a greeting|
|`!bot transcript`|Bot sends the chat transcript as a .txt file|
|`!bot transcript please`|Bot happily sends the transcript :)|
@ -39,7 +30,7 @@ If you prefer to develop locally instead of on Glitch:
Clone the project
```
git clone https://github.com/nomadic-labs/safesupport-bot.git
git clone https://github.com/Safe-Support-Chat/ocrcc-bot.git
```
Install dependencies
@ -48,9 +39,14 @@ cd safesupport-bot
yarn
```
Copy the sample `.env` file and add in your own variables
Copy the sample config file and add in the missing values.
```
cp .env.sample .env
cp sample.config.json config.json
```
Pull in the user-defined settings (if there are any).
```
yarn setup
```
Start the local server

365
dist/bot.js vendored
View File

@ -27,16 +27,18 @@ var _encryptAttachment = _interopRequireDefault(require("./encrypt-attachment"))
global.Olm = require("olm");
const BOT_SIGNAL_END_CHAT = 'END_CHAT';
const BOT_SIGNAL_CHAT_OFFLINE = 'CHAT_OFFLINE';
class OcrccBot {
constructor(botConfig) {
this.config = botConfig;
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
constructor(config) {
this.config = config;
this.client = matrix.createClient(this.config.matrixServerUrl);
this.joinedRooms = [];
this.inactivityTimers = {};
}
createLocalStorage() {
const storageLoc = `matrix-chatbot-${this.config.BOT_USERNAME}`;
const storageLoc = `matrix-chatbot-${this.config.botUsername}`;
const dir = path.resolve(path.join(os.homedir(), ".local-storage"));
if (!fs.existsSync(dir)) {
@ -47,20 +49,20 @@ class OcrccBot {
return new _nodeLocalstorage.LocalStorage(localStoragePath);
}
sendTextMessage(roomId, msgText, showToUser = null) {
async sendTextMessage(roomId, msgText, showToUser = null) {
const content = {
msgtype: "m.text",
body: msgText,
showToUser: showToUser
};
this.sendMessage(roomId, content);
await this.sendMessage(roomId, content);
}
async sendNotice(roomId, message) {
_logger.default.log("info", `SENDING *NOTICE*: ${message}`);
try {
await this.client.sendNotice(roomId, message);
_logger.default.log("info", `SENT *NOTICE*: ${message}`);
} catch (err) {
switch (err["name"]) {
case "UnknownDeviceError":
@ -110,17 +112,9 @@ class OcrccBot {
}
}
inviteUserToRoom(roomId, member) {
try {
this.client.invite(roomId, member);
} catch (err) {
this.handleBotCrash(roomId, err);
}
}
kickUserFromRoom(roomId, member) {
try {
this.client.kick(roomId, member, this.config.KICK_REASON);
this.client.kick(roomId, member, this.config.kickReason);
} catch (err) {
this.handleBotCrash(roomId, err);
@ -128,28 +122,50 @@ 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) {
this.localStorage.setItem(`${roomId}-waiting`, 'true');
let invitations = [];
try {
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
this.localStorage.setItem(`${roomId}-waiting`, 'true');
let invitations = [];
const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId);
const members = Object.keys(roomMembers["joined"]);
members.forEach(memberId => {
const user = this.client.getUser(memberId);
if (user && user.presence !== "offline" && memberId !== this.config.BOT_USERID) {
invitations.push(memberId);
this.inviteUserToRoom(roomId, memberId);
}
});
for (const memberId of members) {
const invited = await this.inviteFacilitatorIfOnline(roomId, memberId);
invitations.push(invited);
}
if (invitations.length > 0) {
if (invitations.filter(i => i).length > 0) {
this.localStorage.setItem(`${roomId}-invitations`, invitations);
} else {
_logger.default.log('info', "NO FACILITATORS ONLINE");
this.sendBotSignal(roomId, BOT_SIGNAL_CHAT_OFFLINE); // send notification to Support Chat Notifications room
this.sendNotice(roomId, "CHAT_OFFLINE");
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.default.log('info', `NO FACILITATORS ONLINE, CHAT CLOSED AT ${closedTime} (room ID: ${roomRef})`);
this.sendTextMessage(this.config.facilitatorRoomId, notification);
}
} catch (err) {
this.handleBotCrash(roomId, err);
@ -159,10 +175,9 @@ class OcrccBot {
}
async uninviteFacilitators(roomId) {
this.localStorage.removeItem(`${roomId}-waiting`);
try {
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
this.localStorage.removeItem(`${roomId}-waiting`);
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId);
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId);
const roomMembersIds = Object.keys(supportRoomMembers["joined"]);
const facilitatorsIds = Object.keys(facilitatorsRoomMembers["joined"]);
@ -181,17 +196,27 @@ class OcrccBot {
handleBotCrash(roomId, error) {
if (roomId) {
this.sendTextMessage(roomId, this.config.BOT_ERROR_MESSAGE);
this.sendTextMessage(roomId, this.config.botErrorMessage);
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT);
}
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, `The Help Bot ran into an error: ${error}. Please verify that the chat service is working.`);
this.sendTextMessage(this.config.facilitatorRoomId, `${this.config.botDisplayName} ran into an error: ${error}. Please verify that the chat service is working.`);
}
handleMessageEvent(event) {
const content = event.getContent(); // do nothing if there's no content
const content = event.getContent();
const sender = event.getSender();
const roomId = event.getRoomId(); // do nothing if there's no content
if (!content) {
return;
} // if it's a chat message and the facilitator has joined, reset the inactivity timeout
const facilitatorId = this.localStorage.getItem(`${roomId}-facilitator`);
if (Boolean(facilitatorId) && sender !== this.config.botUserId) {
this.setInactivityTimeout(roomId);
} // bot commands
@ -200,7 +225,7 @@ class OcrccBot {
} // write to transcript
if (this.config.CAPTURE_TRANSCRIPTS) {
if (this.config.captureTranscripts) {
return this.writeToTranscript(event);
}
}
@ -217,7 +242,7 @@ class OcrccBot {
const filepath = this.localStorage.getItem(`${roomId}-transcript`);
if (!filepath) {
return _logger.default.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}`);
return _logger.default.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}. This message will not be added: ${content.body}`);
}
const message = `${sender} [${time}]: ${content.body}\n`;
@ -236,8 +261,9 @@ class OcrccBot {
}, {
keyword: 'delete transcript',
function: (senderId, roomId) => {
this.deleteTranscript(senderId, roomId);
}
this.deleteTranscript(senderId, roomId, true);
} // delete transcript and send confirmation message
}, {
keyword: 'say',
function: (senderId, roomId, message) => {
@ -250,6 +276,12 @@ class OcrccBot {
const message = responses[Math.floor(Math.random() * responses.length)];
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 {
@ -270,7 +302,7 @@ class OcrccBot {
}
}
async leaveEmptyRooms(senderId) {
async leaveEmptyRooms() {
try {
const roomData = await this.client.getJoinedRooms();
const joinedRoomsIds = roomData["joined_rooms"];
@ -279,16 +311,16 @@ class OcrccBot {
if (room && room.getJoinedMemberCount() === 1) {
try {
_logger.default.log('info', "LEAVING EMPTY ROOM => " + roomId);
await this.client.leave(roomId);
_logger.default.log('info', `LEAVING EMPTY ROOM => ${roomId}`);
} catch (err) {
_logger.default.log('error', "ERROR LEAVING EMPTY ROOM => " + err);
_logger.default.log('error', `ERROR LEAVING ROOM ${roomId} => ${err}`);
}
}
});
} catch (err) {
_logger.default.log("error", `ERROR GETTING JOINED ROOMS: ${err}`);
_logger.default.log("error", `ERROR LEAVING EMPTY ROOMS: ${err}`);
}
}
@ -297,7 +329,7 @@ class OcrccBot {
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
if (!transcriptFile) {
this.sendTextMessage(roomId, "There is no transcript for this chat.", senderId);
this.sendTextMessage(roomId, "Cannot send transcript, there is no transcript for this chat.", senderId);
}
if (this.client.isRoomEncrypted(roomId)) {
@ -356,11 +388,11 @@ class OcrccBot {
}
}
deleteTranscript(senderId, roomId) {
deleteTranscript(senderId, roomId, sendConfirmation = false) {
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`);
if (!transcriptFile) {
return this.sendTextMessage(roomId, "There is no transcript for this chat.", senderId);
return this.sendTextMessage(roomId, "Cannot delete transcript, there is no transcript for this chat.", senderId);
}
fs.unlink(transcriptFile, err => {
@ -372,11 +404,13 @@ class OcrccBot {
return this.sendTextMessage(roomId, `There was an error deleting the transcript: ${err}`, senderId);
}
this.localStorage.removeItem(`${roomId}-transcript`);
if (sendConfirmation) {
this.sendTextMessage(roomId, `The transcript file has been deleted.`, senderId);
}
_logger.default.log('info', "DELETED TRANSCRIPT FILE => " + transcriptFile);
this.sendTextMessage(roomId, `The transcript file has been deleted.`, senderId);
this.localStorage.removeItem(`${roomId}-transcript`);
});
}
@ -394,12 +428,12 @@ class OcrccBot {
const auth = {
session: err.data.session,
type: "m.login.password",
user: this.config.BOT_USERID,
user: this.config.botUserId,
identifier: {
type: "m.id.user",
user: this.config.BOT_USERID
user: this.config.botUserId
},
password: this.config.BOT_PASSWORD
password: this.config.botPassword
};
await this.client.deleteMultipleDevices(oldDevices, auth);
@ -417,7 +451,7 @@ class OcrccBot {
async setMembershipListeners() {
// Automatically accept all room invitations
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.botUserId && !this.joinedRooms.includes(member.roomId)) {
try {
const roomData = await this.client.getJoinedRooms();
const joinedRooms = roomData["joined_rooms"];
@ -432,110 +466,127 @@ class OcrccBot {
const chatTime = inviteDate.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.sendTextMessage(this.config.facilitatorRoomId, notification);
this.inviteFacilitators(room.roomId);
this.setTimeoutforFacilitator(room.roomId);
}
} catch (err) {
_logger.default.log("error", "ERROR JOINING ROOM => " + err);
}
}
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 (member.membership === "join" && member.userId !== this.config.botUserId && this.localStorage.getItem(`${member.roomId}-waiting`)) {
try {
// make sure it's a facilitator joining
const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId);
const members = Object.keys(roomMembers["joined"]);
const isFacilitator = members.includes(member.userId);
if (isFacilitator) {
// made facilitator a moderator in the room
this.localStorage.setItem(`${member.roomId}-facilitator`, member.userId);
const event = {
getType: () => {
return "m.room.power_levels";
},
getContent: () => {
return {
users: {
[this.config.BOT_USERID]: 100,
[member.userId]: 50
}
};
}
};
this.client.setPowerLevel(member.roomId, member.userId, 50, event); // send notification to Support Chat Notifications room
const currentDate = new Date();
const chatTime = currentDate.toLocaleTimeString();
const roomId = member.roomId.split(':')[0];
const notification = `${member.name} joined the chat at ${chatTime} (room ID: ${roomId})`;
this.sendTextMessage(this.config.FACILITATOR_ROOM_ID, notification); // send notification to chat room
this.sendTextMessage(member.roomId, `${member.name} has joined the chat.`); // revoke the other invitations
this.uninviteFacilitators(member.roomId); // set transcript file
if (this.config.CAPTURE_TRANSCRIPTS) {
const currentDate = new Date();
const dateOpts = {
year: "numeric",
month: "short",
day: "numeric"
if (isFacilitator) {
// made facilitator a moderator in the room
this.localStorage.setItem(`${member.roomId}-facilitator`, member.userId);
const event = {
getType: () => {
return "m.room.power_levels";
},
getContent: () => {
return {
users: {
[this.config.botUserId]: 100,
[member.userId]: 50
}
};
}
};
const chatDate = currentDate.toLocaleDateString("en-GB", dateOpts);
const chatTime = currentDate.toLocaleTimeString("en-GB", {
timeZone: "America/New_York"
});
const filename = `${chatDate} - ${chatTime} - ${member.roomId}.txt`;
const filepath = path.resolve(path.join("transcripts", filename));
this.localStorage.setItem(`${member.roomId}-transcript`, filepath);
this.client.setPowerLevel(member.roomId, member.userId, 50, event); // send notification to Support Chat Notifications room
const currentDate = new Date();
const chatTime = currentDate.toLocaleTimeString();
const roomId = member.roomId.split(':')[0];
const notification = `${member.name} joined the chat at ${chatTime} (room ID: ${roomId})`;
this.sendTextMessage(this.config.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);
}
}
} catch (err) {
_logger.default.log("error", `ERROR WHEN FACILITATOR JOINED ROOM ==> ${err}`);
}
}
if (member.membership === "leave" && member.userId !== this.config.BOT_USERID) {
// ensure bot is still in the room
const roomData = await this.client.getJoinedRooms();
const joinedRooms = roomData["joined_rooms"];
const isBotInRoom = joinedRooms.includes(member.roomId);
if (member.membership === "leave" && member.userId !== this.config.botUserId) {
// notify room if the facilitator has left
try {
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`);
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);
if (!room) return; // notify room if the facilitator has left
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`);
if (isBotInRoom && member.userId === facilitatorId) {
this.sendTextMessage(member.roomId, `${member.name} has left the chat.`);
} // leave if there is nobody in the room
if (!room) return;
const roomMembers = await room.getJoinedMembers(); // array
// leave if there is nobody in the room
try {
const memberCount = room.getJoinedMemberCount();
const memberCount = roomMembers.length;
const isBotInRoom = Boolean(roomMembers.find(member => member.userId === this.config.botUserId));
if (memberCount === 1 && isBotInRoom) {
// just the bot left
_logger.default.log("info", `LEAVING EMPTY ROOM ==> ${member.roomId}`);
_logger.default.log("info", `LEAVING EMPTY ROOM: ${member.roomId}`);
this.deleteTranscript(member.userId, member.roomId);
this.localStorage.removeItem(`${member.roomId}-facilitator`);
this.localStorage.removeItem(`${member.roomId}-transcript`);
return this.client.leave(member.roomId);
this.localStorage.removeItem(`${member.roomId}-waiting`);
return await this.client.leave(member.roomId);
}
} catch (err) {
_logger.default.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
return _logger.default.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
} // send signal to close the chat if there are no facilitators in the room
try {
const roomMembers = await room.getJoinedMembers();
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID);
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId); // object
const facilitators = facilitatorRoomMembers['joined'];
let facilitatorInRoom = false;
roomMembers.forEach(member => {
if (member.userId !== this.config.BOT_USERID && Boolean(facilitators[member.userId])) {
if (member.userId !== this.config.botUserId && Boolean(facilitators[member.userId])) {
facilitatorInRoom = true;
}
});
if (!facilitatorInRoom) {
_logger.default.log("info", `NO FACILITATORS LEFT, SENDING SIGNAL TO END CHAT`);
this.sendBotSignal(member.roomId, BOT_SIGNAL_END_CHAT);
}
} catch (err) {
@ -545,6 +596,42 @@ 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() {
// encrypted messages
this.client.on("Event.decrypted", (event, err) => {
@ -564,43 +651,36 @@ class OcrccBot {
});
}
async leaveOldRooms() {
const roomData = await this.client.getJoinedRooms();
roomData["joined_rooms"].forEach(async roomId => {
try {
await this.client.leave(roomId);
} catch (err) {
_logger.default.log('error', "ERROR LEAVING ROOM => " + err);
}
});
}
async sendBotSignal(roomId, signal, args) {
let content = {
signal: signal,
args: args
};
await this.client.sendStateEvent(roomId, 'm.bot.signal', content);
try {
await this.client.sendStateEvent(roomId, 'm.bot.signal', content);
} catch (err) {
_logger.default.log('error', "ERROR SENDING BOT SIGNAL => " + err);
}
}
async start() {
const localStorage = this.createLocalStorage();
this.localStorage = localStorage;
try {
const localStorage = this.createLocalStorage();
this.localStorage = localStorage;
const auth = {
user: this.config.BOT_USERNAME,
password: this.config.BOT_PASSWORD,
initial_device_display_name: this.config.BOT_DISPLAY_NAME
user: this.config.botUsername,
password: this.config.botPassword,
initial_device_display_name: this.config.botDisplayName
};
const account = await this.client.login("m.login.password", auth);
_logger.default.log("info", `ACCOUNT ==> ${JSON.stringify(account)}`);
let opts = {
baseUrl: this.config.MATRIX_SERVER_URL,
baseUrl: this.config.matrixServerUrl,
accessToken: account.access_token,
userId: this.config.BOT_USERID,
userId: this.config.botUserId,
deviceId: account.device_id,
sessionStore: new matrix.WebStorageSessionStore(localStorage)
};
@ -614,6 +694,7 @@ class OcrccBot {
if (state === 'PREPARED') {
await this.deleteOldDevices();
await this.leaveEmptyRooms();
await this.trackJoinedRooms();
await this.setMembershipListeners();
await this.setMessageListeners();

14
dist/bot.test.js vendored
View File

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

39
dist/index.js vendored
View File

@ -2,37 +2,14 @@
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _config = _interopRequireDefault(require("../config.json"));
var _bot = _interopRequireDefault(require("./bot"));
require('dotenv').config();
const bot = new _bot.default(_config.default);
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,
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();
try {
bot.start();
} catch (err) {
console.log("Unable to start bot", err);
}

54
dist/setup.js vendored Normal file
View File

@ -0,0 +1,54 @@
"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();

View File

@ -1,11 +1,12 @@
{
"name": "private-safesupport-bot",
"version": "1.2.0",
"version": "3.1.0",
"description": "Chatbot to manage interactions on Safe Support Chat",
"main": "dist/index.js",
"scripts": {
"develop": "nodemon --exec babel-node src/index.js",
"build": "babel src -d dist",
"setup": "node src/setup.js",
"start": "yarn build && node dist/index.js",
"test": "jest"
},
@ -14,6 +15,7 @@
"dependencies": {
"dotenv": "^8.2.0",
"matrix-js-sdk": "^6.2.1",
"node-fetch": "^2.6.1",
"node-localstorage": "^2.1.5",
"node-webcrypto-ossl": "^2.1.0",
"olm": "https://packages.matrix.org/npm/olm/olm-3.1.4.tgz",

16
sample.config.json Normal file
View File

@ -0,0 +1,16 @@
{
"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
}

View File

@ -12,18 +12,18 @@ import logger from "./logger";
import encrypt from "./encrypt-attachment";
const BOT_SIGNAL_END_CHAT = 'END_CHAT'
const BOT_SIGNAL_CHAT_OFFLINE = 'CHAT_OFFLINE'
class OcrccBot {
constructor(botConfig) {
this.config = botConfig
this.client = matrix.createClient(this.config.MATRIX_SERVER_URL);
constructor(config) {
this.config = config
this.client = matrix.createClient(this.config.matrixServerUrl);
this.joinedRooms = [];
this.inactivityTimers = {};
}
createLocalStorage() {
const storageLoc = `matrix-chatbot-${this.config.BOT_USERNAME}`;
const storageLoc = `matrix-chatbot-${this.config.botUsername}`;
const dir = path.resolve(path.join(os.homedir(), ".local-storage"));
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
@ -32,21 +32,20 @@ class OcrccBot {
return new LocalStorage(localStoragePath);
}
sendTextMessage(roomId, msgText, showToUser = null) {
async sendTextMessage(roomId, msgText, showToUser = null) {
const content = {
msgtype: "m.text",
body: msgText,
showToUser: showToUser
};
this.sendMessage(roomId, content);
await this.sendMessage(roomId, content);
}
async sendNotice(roomId, message) {
logger.log("info", `SENDING *NOTICE*: ${message}`)
try {
await this.client.sendNotice(roomId, message)
logger.log("info", `SENT *NOTICE*: ${message}`)
} catch(err) {
switch (err["name"]) {
case "UnknownDeviceError":
@ -91,48 +90,59 @@ class OcrccBot {
}
}
inviteUserToRoom(roomId, member) {
try {
this.client.invite(roomId, member)
} catch(err) {
this.handleBotCrash(roomId, err);
}
}
kickUserFromRoom(roomId, member) {
try {
this.client.kick(roomId, member, this.config.KICK_REASON)
this.client.kick(roomId, member, this.config.kickReason)
} catch(err) {
this.handleBotCrash(roomId, err);
logger.log("error", `ERROR KICKING OUT MEMBER: ${err}`);
}
}
async inviteFacilitators(roomId) {
this.localStorage.setItem(`${roomId}-waiting`, 'true')
let invitations = []
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) {
try {
const roomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID)
this.localStorage.setItem(`${roomId}-waiting`, 'true')
let invitations = []
const roomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId)
const members = Object.keys(roomMembers["joined"]);
members.forEach(memberId => {
const user = this.client.getUser(memberId);
if (
user &&
(user.presence !== "offline") &&
memberId !== this.config.BOT_USERID
) {
invitations.push(memberId)
this.inviteUserToRoom(roomId, memberId);
}
});
for (const memberId of members) {
const invited = await this.inviteFacilitatorIfOnline(roomId, memberId)
invitations.push(invited)
}
if (invitations.length > 0) {
if (invitations.filter(i => i).length > 0) {
this.localStorage.setItem(`${roomId}-invitations`, invitations)
} else {
logger.log('info', "NO FACILITATORS ONLINE")
this.sendNotice(roomId, "CHAT_OFFLINE")
this.sendBotSignal(roomId, BOT_SIGNAL_CHAT_OFFLINE)
// 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) {
@ -143,10 +153,9 @@ class OcrccBot {
async uninviteFacilitators(roomId) {
this.localStorage.removeItem(`${roomId}-waiting`)
try {
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.FACILITATOR_ROOM_ID)
this.localStorage.removeItem(`${roomId}-waiting`)
const facilitatorsRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId)
const supportRoomMembers = await this.client.getJoinedRoomMembers(roomId)
const roomMembersIds = Object.keys(supportRoomMembers["joined"]);
@ -168,12 +177,13 @@ class OcrccBot {
handleBotCrash(roomId, error) {
if (roomId) {
this.sendTextMessage(roomId, this.config.BOT_ERROR_MESSAGE);
this.sendTextMessage(roomId, this.config.botErrorMessage);
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
}
this.sendTextMessage(
this.config.FACILITATOR_ROOM_ID,
`The Help Bot ran into an error: ${error}. Please verify that the chat service is working.`
this.config.facilitatorRoomId,
`${this.config.botDisplayName} ran into an error: ${error}. Please verify that the chat service is working.`
);
}
@ -189,7 +199,7 @@ class OcrccBot {
// if it's a chat message and the facilitator has joined, reset the inactivity timeout
const facilitatorId = this.localStorage.getItem(`${roomId}-facilitator`)
if (Boolean(facilitatorId) && sender !== this.config.BOT_USERID) {
if (Boolean(facilitatorId) && sender !== this.config.botUserId) {
this.setInactivityTimeout(roomId)
}
@ -199,7 +209,7 @@ class OcrccBot {
}
// write to transcript
if (this.config.CAPTURE_TRANSCRIPTS) {
if (this.config.captureTranscripts) {
return this.writeToTranscript(event);
}
}
@ -216,7 +226,7 @@ class OcrccBot {
const filepath = this.localStorage.getItem(`${roomId}-transcript`)
if (!filepath) {
return logger.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}`);
return logger.log("error", `NO TRANSCRIPT FILE FOR ROOM: ${roomId}. This message will not be added: ${content.body}`);
}
const message = `${sender} [${time}]: ${content.body}\n`;
@ -235,7 +245,7 @@ class OcrccBot {
},
{
keyword: 'delete transcript',
function: (senderId, roomId) => { this.deleteTranscript(senderId, roomId) }
function: (senderId, roomId) => { this.deleteTranscript(senderId, roomId, true) } // delete transcript and send confirmation message
},
{
keyword: 'say',
@ -256,6 +266,13 @@ class OcrccBot {
const message = responses[Math.floor(Math.random() * responses.length)];
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 {
@ -280,7 +297,7 @@ class OcrccBot {
}
}
async leaveEmptyRooms(senderId) {
async leaveEmptyRooms() {
try {
const roomData = await this.client.getJoinedRooms()
const joinedRoomsIds = roomData["joined_rooms"]
@ -288,15 +305,15 @@ class OcrccBot {
const room = this.client.getRoom(roomId)
if (room && room.getJoinedMemberCount() === 1) {
try {
logger.log('info', "LEAVING EMPTY ROOM => " + roomId)
await this.client.leave(roomId)
logger.log('info', `LEAVING EMPTY ROOM => ${roomId}`)
} catch(err) {
logger.log('error', "ERROR LEAVING EMPTY ROOM => " + err)
logger.log('error', `ERROR LEAVING ROOM ${roomId} => ${err}`)
}
}
})
} catch(err) {
logger.log("error", `ERROR GETTING JOINED ROOMS: ${err}`);
logger.log("error", `ERROR LEAVING EMPTY ROOMS: ${err}`);
}
}
@ -307,7 +324,7 @@ class OcrccBot {
if (!transcriptFile) {
this.sendTextMessage(
roomId,
"There is no transcript for this chat.",
"Cannot send transcript, there is no transcript for this chat.",
senderId
);
}
@ -370,13 +387,13 @@ class OcrccBot {
}
}
deleteTranscript(senderId, roomId) {
deleteTranscript(senderId, roomId, sendConfirmation=false) {
const transcriptFile = this.localStorage.getItem(`${roomId}-transcript`)
if (!transcriptFile) {
return this.sendTextMessage(
roomId,
"There is no transcript for this chat.",
"Cannot delete transcript, there is no transcript for this chat.",
senderId
);
}
@ -392,13 +409,17 @@ class OcrccBot {
senderId
);
}
this.localStorage.removeItem(`${roomId}-transcript`)
if (sendConfirmation) {
this.sendTextMessage(
roomId,
`The transcript file has been deleted.`,
senderId
);
}
logger.log('info', "DELETED TRANSCRIPT FILE => " + transcriptFile)
this.sendTextMessage(
roomId,
`The transcript file has been deleted.`,
senderId
);
this.localStorage.removeItem(`${roomId}-transcript`)
});
}
@ -415,9 +436,9 @@ class OcrccBot {
const auth = {
session: err.data.session,
type: "m.login.password",
user: this.config.BOT_USERID,
identifier: { type: "m.id.user", user: this.config.BOT_USERID },
password: this.config.BOT_PASSWORD
user: this.config.botUserId,
identifier: { type: "m.id.user", user: this.config.botUserId },
password: this.config.botPassword
};
await this.client.deleteMultipleDevices(oldDevices, auth)
@ -436,7 +457,7 @@ class OcrccBot {
this.client.on("RoomMember.membership", async (event, member) => {
if (
member.membership === "invite" &&
member.userId === this.config.BOT_USERID &&
member.userId === this.config.botUserId &&
!this.joinedRooms.includes(member.roomId)
) {
try {
@ -450,7 +471,7 @@ class OcrccBot {
const chatTime = inviteDate.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.sendTextMessage(this.config.facilitatorRoomId, notification);
this.inviteFacilitators(room.roomId)
this.setTimeoutforFacilitator(room.roomId)
}
@ -461,12 +482,12 @@ class OcrccBot {
if (
member.membership === "join" &&
member.userId !== this.config.BOT_USERID &&
member.userId !== this.config.botUserId &&
this.localStorage.getItem(`${member.roomId}-waiting`)
) {
try {
// 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 isFacilitator = members.includes(member.userId)
@ -480,7 +501,7 @@ class OcrccBot {
getContent: () => {
return {
users: {
[this.config.BOT_USERID]: 100,
[this.config.botUserId]: 100,
[member.userId]: 50
}
};
@ -493,7 +514,7 @@ class OcrccBot {
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);
this.sendTextMessage(this.config.facilitatorRoomId, notification);
// send notification to chat room
this.sendTextMessage(
@ -505,7 +526,7 @@ class OcrccBot {
this.uninviteFacilitators(member.roomId);
// set transcript file
if (this.config.CAPTURE_TRANSCRIPTS) {
if (this.config.captureTranscripts) {
const currentDate = new Date();
const dateOpts = {
year: "numeric",
@ -528,54 +549,62 @@ class OcrccBot {
if (
member.membership === "leave" &&
member.userId !== this.config.BOT_USERID
member.userId !== this.config.botUserId
) {
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
try {
const facilitatorId = this.localStorage.getItem(`${member.roomId}-facilitator`)
if (isBotInRoom && member.userId === facilitatorId) {
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.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
try {
const memberCount = roomMembers.length
const isBotInRoom = Boolean(roomMembers.find(member => member.userId === this.config.botUserId))
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.localStorage.removeItem(`${member.roomId}-facilitator`)
this.localStorage.removeItem(`${member.roomId}-transcript`)
return this.client.leave(member.roomId)
this.localStorage.removeItem(`${member.roomId}-waiting`)
return await this.client.leave(member.roomId)
}
} catch(err) {
logger.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
return logger.log("error", `ERROR LEAVING EMPTY ROOM ==> ${err}`);
}
// send signal to close the chat if there are no facilitators in the room
try {
const facilitatorRoomMembers = await this.client.getJoinedRoomMembers(this.config.facilitatorRoomId) // object
const facilitators = facilitatorRoomMembers['joined']
let facilitatorInRoom = false;
roomMembers.forEach(member => {
if (member.userId !== this.config.BOT_USERID && Boolean(facilitators[member.userId])) {
if (member.userId !== this.config.botUserId && Boolean(facilitators[member.userId])) {
facilitatorInRoom = true
}
})
if (!facilitatorInRoom) {
logger.log("info", `NO FACILITATORS LEFT, SENDING SIGNAL TO END CHAT`);
this.sendBotSignal(member.roomId, BOT_SIGNAL_END_CHAT)
}
@ -587,12 +616,24 @@ class OcrccBot {
}
setTimeoutforFacilitator(roomId) {
setTimeout(() => {
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.log("info", `NO FACILITATORS JOINED THE CHAT WITHIN THE MAXIMUM WAIT TIME, CHAT CLOSED AT ${closedTime} (room ID: ${roomRef})`);
}
}, this.config.MAX_WAIT_TIME)
}, this.config.maxWaitTime * 1000) // convert seconds to milliseconds
}
setInactivityTimeout(roomId) {
@ -602,13 +643,14 @@ class OcrccBot {
clearTimeout(oldTimeout);
}
const newTimeout = setTimeout(() => {
this.sendTextMessage(
const newTimeout = setTimeout(async() => {
logger.log("info", `CHAT IS INACTIVE, SENDING SIGNAL TO END CHAT`);
await this.sendTextMessage(
roomId,
`This chat has been closed due to inactivity.`
this.config.chatInactiveMessage
);
this.sendBotSignal(roomId, BOT_SIGNAL_END_CHAT)
}, this.config.MAX_INACTIVE)
}, this.config.maxInactiveTime * 1000) // convert seconds to milliseconds
this.inactivityTimers[roomId] = newTimeout;
}
@ -631,18 +673,6 @@ class OcrccBot {
});
}
async leaveOldRooms() {
const roomData = await this.client.getJoinedRooms()
roomData["joined_rooms"].forEach(async roomId => {
try {
await this.client.leave(roomId)
} catch(err) {
logger.log('error', "ERROR LEAVING ROOM => " + err)
}
})
}
async sendBotSignal (roomId, signal, args) {
let content = {
signal: signal,
@ -656,22 +686,22 @@ class OcrccBot {
}
async start() {
const localStorage = this.createLocalStorage();
this.localStorage = localStorage
try {
const localStorage = this.createLocalStorage();
this.localStorage = localStorage
const auth = {
user: this.config.BOT_USERNAME,
password: this.config.BOT_PASSWORD,
initial_device_display_name: this.config.BOT_DISPLAY_NAME
user: this.config.botUsername,
password: this.config.botPassword,
initial_device_display_name: this.config.botDisplayName
}
const account = await this.client.login("m.login.password", auth)
logger.log("info", `ACCOUNT ==> ${JSON.stringify(account)}`);
let opts = {
baseUrl: this.config.MATRIX_SERVER_URL,
baseUrl: this.config.matrixServerUrl,
accessToken: account.access_token,
userId: this.config.BOT_USERID,
userId: this.config.botUserId,
deviceId: account.device_id,
sessionStore: new matrix.WebStorageSessionStore(localStorage)
};
@ -684,6 +714,7 @@ class OcrccBot {
logger.log("info", `SYNC STATUS: ${state}`)
if (state === 'PREPARED') {
await this.deleteOldDevices()
await this.leaveEmptyRooms()
await this.trackJoinedRooms()
await this.setMembershipListeners();
await this.setMessageListeners();

View File

@ -1,42 +1,9 @@
require('dotenv').config()
import config from '../config.json';
import OcrccBot from './bot';
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,
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,
const bot = new OcrccBot(config);
try {
bot.start();
} catch(err) {
console.log("Unable to start bot", err)
}
import OcrccBot from './bot'
const bot = new OcrccBot(botConfig);
bot.start();

50
src/setup.js Normal file
View File

@ -0,0 +1,50 @@
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();

View File

@ -3954,6 +3954,11 @@ node-environment-flags@^1.0.5:
object.getownpropertydescriptors "^2.0.3"
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:
version "0.4.0"
resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b"