-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
104 lines (92 loc) · 2.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
require('dotenv').config();
const WebSocket = require('ws');
const express = require('express');
const server = require('http').createServer(express());
const wss = new WebSocket.Server({ server });
const twlo = require('twilio')(process.env.ACCOUNT_SID, process.env.AUTH_TOKEN);
const speech = require('@google-cloud/speech');
const speechClient = new speech.SpeechClient();
//Configure Transcription Request
const request = {
config: {
encoding: 'MULAW',
sampleRateHertz: 8000,
languageCode: 'en-US',
model: 'phone_call',
use_enhanced: true
},
interimResults: true
};
let currentCall;
let idx = 0;
function sendTwiML(twiml) {
currentCall.update({ twiml }).then(r => {
console.log('sent twiml', twiml);
});
};
// This is built against a very simple IVR that requests you select 1 for sales or support
// It then announces that it's connecting you to sales or support and forwards the call
// As such, the patterns we search for are "sales" and "connecting" to know we reached those prompts.
const steps = [
{pattern: /sales/, trigger: () => {
console.log('Detected sales or support prompt');
sendTwiML('<Response><Play digits="1" /><Pause length="15" /></Response>');
idx++;
}},
{pattern: /connecting/, trigger: () => {
console.log('Found last IVR widget, ending call');
currentCall.update({status: 'completed'});
process.exit(1);
}}
];
wss.on('connection', ws => {
console.log('New Connection Initiated');
let recognizeStream = null;
ws.on('message', message => {
const msg = JSON.parse(message);
switch (msg.event) {
case 'connected':
console.log('A new call has connected.');
recognizeStream = speechClient
.streamingRecognize(request)
.on('error', console.error)
.on('data', data => {
const transcript = data.results[0].alternatives[0].transcript;
if (!!+process.env.VERBOSE) {
console.log(transcript);
}
if (transcript.match(steps[idx].pattern)) {
steps[idx].trigger(transcript);
}
});
break;
case 'start':
console.log(`Starting Media Stream ${msg.streamSid}`);
break;
case 'media':
recognizeStream.write(msg.media.payload);
break;
case 'stop':
console.log('Call Has Ended');
recognizeStream.destroy();
break;
}
});
});
server.listen(8080);
console.log('Websocket server started');
console.log('Initiating call to IVR');
twlo.calls
.create({
twiml: `
<Response>
<Start><Stream url="${process.env.HOST}"/></Start>
<Pause length="60" />
</Response>`,
to: process.env.FROM_DID,
from: process.env.TO_DID
})
.then(call => {
console.log('Created call', call.sid);
currentCall = call;
});