-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapp.py
103 lines (78 loc) · 2.82 KB
/
app.py
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
import os
from flask import Flask, request
from twilio.twiml.voice_response import VoiceResponse
from utils.voiceflow_helpers import VoiceFlow
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
if request.method == 'POST':
language = 'en-US'
voice = 'alice'
timeout = 5
request_data = request.form
tw_resp = VoiceResponse()
vf = VoiceFlow(
vf_id=os.getenv('VF_PROJECT_VERSION_ID'),
vf_api_key=os.getenv('VF_API_KEY'),
user_id=request_data['From'],
)
vf_messages = []
if request_data['CallStatus'] == 'ringing':
vf_messages = vf.interact(content_type='launch')
else:
if 'Digits' in request_data:
digits = request_data['Digits']
try:
choices = vf.fetch_state()['variables']['choices']
except Exception as e:
print(e)
else:
if choices != 0:
choices = choices.split('|')
if len(choices) >= int(digits):
vf_messages = vf.interact(
user_input=choices[int(digits) - 1]
)
vf.update_variable(
variable_name='choices',
variable_value=0,
)
else:
vf_messages = vf.interact(user_input=digits)
elif 'SpeechResult' in request_data:
vf_messages = vf.interact(
user_input=request_data['SpeechResult']
)
for message in vf_messages:
if message.type == 'text':
tw_resp.say(
message=message.data,
voice=voice,
language=language,
)
elif message.type == 'audio':
tw_resp.play(
url=message.data,
)
elif message.type == 'choices':
vf.update_variable(
variable_name='choices',
variable_value='|'.join(choice['name'] for choice in message.data),
)
elif message.type == 'call_forwarding':
tw_resp.dial(message.data)
elif message.type == 'end':
tw_resp.hangup()
tw_resp.gather(
input='dtmf speech',
language=language,
timeout=timeout,
speech_model='numbers_and_commands',
finish_on_key='#',
enhanced=True,
)
return str(tw_resp)
else:
return 'VoiceFlow - Twilio IVR'
if __name__ == '__main__':
app.run()