@@ -14,7 +14,11 @@ require('dotenv').config();
1414const { THERAPIST_PASSWORD , THERAPIST_EMAIL_ADDRESS , ENVIRONMENT } = process . env ;
1515let { RASA_AGENT_URL } = process . env ;
1616RASA_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
1923const chatSdk = new Chat ( ) ;
2024let 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