Skip to content

Commit 5ac7d8c

Browse files
authored
Merge pull request #17 from PerfectFit-project/360-messages-spped
speed dependant on length
2 parents f42b5d6 + 848491c commit 5ac7d8c

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

niceday-broker/index.js

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,11 @@ require('dotenv').config();
1414
const { THERAPIST_PASSWORD, THERAPIST_EMAIL_ADDRESS, ENVIRONMENT } = process.env;
1515
let { RASA_AGENT_URL } = process.env;
1616
RASA_AGENT_URL = (RASA_AGENT_URL === undefined) ? 'http://rasa_server:5005/webhooks/rest/webhook' : RASA_AGENT_URL;
17-
const MESSAGE_DELAY = 3000; // Delay in between messages in ms
17+
// proportional factor between the number of words in a message and the time to wait before the
18+
// newt message is delivered
19+
const WORDS_PER_SECOND = 5;
20+
// maximum delay between a message and the next one
21+
const MAX_DELAY = 10;
1822

1923
const chatSdk = new Chat();
2024
let selectedServer;
@@ -73,22 +77,28 @@ function sleep(ms) {
7377
* Handle the response from rasa, send each message to the Niceday user.
7478
* We insert a delay in between messages, so the user has some time to read each message.
7579
* */
76-
function onRasaResponse() {
80+
async function onRasaResponse() {
7781
if (this.readyState === 4 && this.status === 200) {
7882
const responseJson = JSON.parse(this.responseText);
79-
responseJson.forEach(async (message, i) => {
80-
if (ENVIRONMENT === 'prod') {
81-
await sleep(i * MESSAGE_DELAY);
82-
}
83+
84+
const processMessage = async (message) => {
8385
const attachment = {
8486
replyOfId: null,
85-
attachmentIds: [],
87+
attachmentIds: message.metadata || [],
8688
};
87-
if ('metadata' in message) {
88-
attachment.attachmentIds = message.metadata;
89-
}
89+
9090
sendMessage(message.text, parseInt(message.recipient_id, 10), attachment);
91-
});
91+
92+
if (ENVIRONMENT === 'prod') {
93+
const delay = Math.min(MAX_DELAY, message.text.split(' ').length / WORDS_PER_SECOND);
94+
await sleep(delay * 1000);
95+
}
96+
};
97+
98+
await responseJson.reduce(async (prevPromise, message) => {
99+
await prevPromise;
100+
await processMessage(message);
101+
}, Promise.resolve());
92102
} else if (this.readyState === 4) {
93103
console.log('Something went wrong, status:', this.status, this.responseText);
94104
}

0 commit comments

Comments
 (0)