Repository navigation
Expand file tree
/
Copy pathtwiml.py
More file actions
473 lines (355 loc) · 13.7 KB
/
Copy pathtwiml.py
File metadata and controls
473 lines (355 loc) · 13.7 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
"""
Make sure to check out the TwiML overview and tutorial
"""
import xml.etree.ElementTree as ET
class TwimlException(Exception):
pass
class Verb(object):
"""Twilio basic verb object.
"""
GET = "GET"
POST = "POST"
nestables = None
def __init__(self, **kwargs):
self.name = self.__class__.__name__
self.body = None
self.verbs = []
self.attrs = {}
if kwargs.get("waitMethod", "GET") not in ["GET", "POST"]:
raise TwimlException("Invalid waitMethod parameter, "
"must be 'GET' or 'POST'")
if kwargs.get("method", "GET") not in ["GET", "POST"]:
raise TwimlException("Invalid method parameter, "
"must be 'GET' or 'POST'")
for k, v in kwargs.items():
if k == "sender":
k = "from"
if v is not None:
self.attrs[k] = v
def __str__(self):
return self.toxml()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
return False
def toxml(self, xml_declaration=True):
"""
Return the contents of this verb as an XML string
:param bool xml_declaration: Include the XML declaration. Defaults to
True
"""
xml = ET.tostring(self.xml()).encode("utf-8")
if xml_declaration:
return u'<?xml version="1.0" encoding="UTF-8"?>' + xml
else:
return xml
def xml(self):
el = ET.Element(self.name)
keys = self.attrs.keys()
keys.sort()
for a in keys:
value = self.attrs[a]
if isinstance(value, bool):
el.set(a, str(value).lower())
else:
el.set(a, str(value))
if self.body:
el.text = self.body
for verb in self.verbs:
el.append(verb.xml())
return el
def append(self, verb):
if not self.nestables or verb.name not in self.nestables:
raise TwimlException("%s is not nestable inside %s" %
(verb.name, self.name))
self.verbs.append(verb)
return verb
class Response(Verb):
"""Twilio response object."""
nestables = [
'Say',
'Play',
'Gather',
'Record',
'Dial',
'Redirect',
'Pause',
'Hangup',
'Reject',
'Sms',
'Enqueue',
'Leave'
]
def __init__(self, **kwargs):
"""Version: Twilio API version e.g. 2008-08-01 """
super(Response, self).__init__(**kwargs)
def say(self, text, **kwargs):
"""Return a newly created :class:`Say` verb, nested inside this
:class:`Response` """
return self.append(Say(text, **kwargs))
def play(self, url, **kwargs):
"""Return a newly created :class:`Play` verb, nested inside this
:class:`Response` """
return self.append(Play(url, **kwargs))
def pause(self, **kwargs):
"""Return a newly created :class:`Pause` verb, nested inside this
:class:`Response` """
return self.append(Pause(**kwargs))
def redirect(self, url=None, **kwargs):
"""Return a newly created :class:`Redirect` verb, nested inside this
:class:`Response` """
return self.append(Redirect(url, **kwargs))
def hangup(self, **kwargs):
"""Return a newly created :class:`Hangup` verb, nested inside this
:class:`Response` """
return self.append(Hangup(**kwargs))
def reject(self, reason=None, **kwargs):
"""Return a newly created :class:`Hangup` verb, nested inside this
:class:`Response` """
return self.append(Reject(reason=reason, **kwargs))
def gather(self, **kwargs):
"""Return a newly created :class:`Gather` verb, nested inside this
:class:`Response` """
return self.append(Gather(**kwargs))
def dial(self, number=None, **kwargs):
"""Return a newly created :class:`Dial` verb, nested inside this
:class:`Response` """
return self.append(Dial(number, **kwargs))
def enqueue(self, name, **kwargs):
"""Return a newly created :class:`Enqueue` verb, nested inside this
:class:`Response` """
return self.append(Enqueue(name, **kwargs))
def leave(self, **kwargs):
"""Return a newly created :class:`Leave` verb, nested inside this
:class:`Response` """
return self.append(Leave(**kwargs))
def record(self, **kwargs):
"""Return a newly created :class:`Record` verb, nested inside this
:class:`Response` """
return self.append(Record(**kwargs))
def sms(self, msg, **kwargs):
"""Return a newly created :class:`Sms` verb, nested inside this
:class:`Response` """
return self.append(Sms(msg, **kwargs))
# All add* methods are deprecated
def addSay(self, *args, **kwargs):
return self.say(*args, **kwargs)
def addPlay(self, *args, **kwargs):
return self.play(*args, **kwargs)
def addPause(self, *args, **kwargs):
return self.pause(*args, **kwargs)
def addRedirect(self, *args, **kwargs):
return self.redirect(*args, **kwargs)
def addHangup(self, *args, **kwargs):
return self.hangup(*args, **kwargs)
def addReject(self, *args, **kwargs):
return self.reject(*args, **kwargs)
def addGather(self, *args, **kwargs):
return self.gather(*args, **kwargs)
def addDial(self, *args, **kwargs):
return self.dial(*args, **kwargs)
def addRecord(self, *args, **kwargs):
return self.record(*args, **kwargs)
def addSms(self, *args, **kwargs):
return self.sms(*args, **kwargs)
class Say(Verb):
"""The :class:`Say` verb converts text to speech that is read back to the
caller.
:param voice: allows you to choose a male or female voice to read text
back.
:param language: allows you pick a voice with a specific language's accent
and pronunciations. Twilio currently supports languages
'en' (English), 'es' (Spanish), 'fr' (French), and 'de'
(German), 'en-gb' (English Great Britain").
:param loop: specifies how many times you'd like the text repeated.
Specifying '0' will cause the the :class:`Say` verb to loop
until the call is hung up.
"""
MAN = 'man'
WOMAN = 'woman'
ENGLISH = 'en'
BRITISH = 'en-gb'
SPANISH = 'es'
FRENCH = 'fr'
GERMAN = 'de'
def __init__(self, text, **kwargs):
super(Say, self).__init__(**kwargs)
self.body = text
class Play(Verb):
"""Play an audio file at a URL
:param url: point to af audio file. The MIME type on the file must be set
correctly.
:param loop: specifies how many times you'd like the text repeated.
Specifying '0' will cause the the :class:`Say` verb to loop
until the call is hung up. Defaults to 1.
"""
def __init__(self, url, **kwargs):
super(Play, self).__init__(**kwargs)
self.body = url
class Pause(Verb):
"""Pause the call
:param length: specifies how many seconds Twilio will wait silently before
continuing on.
"""
class Redirect(Verb):
"""Redirect call flow to another URL
:param url: specifies the url which Twilio should query to retrieve new
TwiML. The default is the current url
:param method: specifies the HTTP method to use when retrieving the url
"""
GET = 'GET'
POST = 'POST'
def __init__(self, url="", **kwargs):
super(Redirect, self).__init__(**kwargs)
self.body = url
class Hangup(Verb):
"""Hangup the call
"""
class Reject(Verb):
"""Hangup the call
:param reason: not sure
"""
class Gather(Verb):
"""Gather digits from the caller's keypad
:param action: URL to which the digits entered will be sent
:param method: submit to 'action' url using GET or POST
:param numDigits: how many digits to gather before returning
:param timeout: wait for this many seconds before returning
:param finishOnKey: key that triggers the end of caller input
"""
GET = 'GET'
POST = 'POST'
nestables = ['Say', 'Play', 'Pause']
def __init__(self, **kwargs):
super(Gather, self).__init__(**kwargs)
def say(self, text, **kwargs):
return self.append(Say(text, **kwargs))
def play(self, url, **kwargs):
return self.append(Play(url, **kwargs))
def pause(self, **kwargs):
return self.append(Pause(**kwargs))
def addSay(self, *args, **kwargs):
return self.say(*args, **kwargs)
def addPlay(self, *args, **kwargs):
return self.play(*args, **kwargs)
def addPause(self, *args, **kwargs):
return self.pause(*args, **kwargs)
class Number(Verb):
"""Specify phone number in a nested Dial element.
:param number: phone number to dial
:param sendDigits: key to press after connecting to the number
"""
def __init__(self, number, **kwargs):
super(Number, self).__init__(**kwargs)
self.body = number
class Client(Verb):
"""Specify a client name to call in a nested Dial element.
:param name: Client name to connect to
"""
def __init__(self, name, **kwargs):
super(Client, self).__init__(**kwargs)
self.body = name
class Sms(Verb):
""" Send a Sms Message to a phone number
:param to: whom to send message to
:param sender: whom to send message from.
:param action: url to request after the message is queued
:param method: submit to 'action' url using GET or POST
:param statusCallback: url to hit when the message is actually sent
"""
GET = 'GET'
POST = 'POST'
def __init__(self, msg, **kwargs):
super(Sms, self).__init__(**kwargs)
self.body = msg
class Conference(Verb):
"""Specify conference in a nested Dial element.
:param name: friendly name of conference
:param bool muted: keep this participant muted
:param bool beep: play a beep when this participant enters/leaves
:param bool startConferenceOnEnter: start conf when this participants joins
:param bool endConferenceOnExit: end conf when this participants leaves
:param waitUrl: TwiML url that executes before conference starts
:param waitMethod: HTTP method for waitUrl GET/POST
"""
GET = 'GET'
POST = 'POST'
def __init__(self, name, **kwargs):
super(Conference, self).__init__(**kwargs)
self.body = name
class Dial(Verb):
"""Dial another phone number and connect it to this call
:param action: submit the result of the dial to this URL
:param method: submit to 'action' url using GET or POST
:param int timeout: The number of seconds to waits for the called
party to answer the call
:param bool hangupOnStar: Allow the calling party to hang up on the
called party by pressing the '*' key
:param int timeLimit: The maximum duration of the Call in seconds
:param callerId: The caller ID that will appear to the called party
:param bool record: Record both legs of a call within this <Dial>
"""
GET = 'GET'
POST = 'POST'
nestables = ['Number', 'Conference', 'Client', 'Queue']
def __init__(self, number=None, **kwargs):
super(Dial, self).__init__(**kwargs)
if number and len(number.split(',')) > 1:
for n in number.split(','):
self.append(Number(n.strip()))
else:
self.body = number
def client(self, name, **kwargs):
return self.append(Client(name, **kwargs))
def number(self, number, **kwargs):
return self.append(Number(number, **kwargs))
def conference(self, name, **kwargs):
return self.append(Conference(name, **kwargs))
def queue(self, name, **kwargs):
return self.append(Queue(name, **kwargs))
def addNumber(self, *args, **kwargs):
return self.number(*args, **kwargs)
def addConference(self, *args, **kwargs):
return self.conference(*args, **kwargs)
class Queue(Verb):
"""Specify queue in a nested Dial element.
60F3
div>
:param name: friendly name for the queue
:param url: url to a twiml document that executes after a call is dequeued
and before the call is connected
:param method: HTTP method for url GET/POST
"""
GET = 'GET'
POST = 'POST'
def __init__(self, name, **kwargs):
super(Queue, self).__init__(**kwargs)
self.body = name
class Enqueue(Verb):
"""Enqueue the call into a specific queue.
:param name: friendly name for the queue
:param action: url to a twiml document that executes when the call
leaves the queue. When dequeued via a <Dial> verb,
this url is executed after the bridged parties disconnect
:param method: HTTP method for action GET/POST
:param wait_url: url to a twiml document that executes
while the call is on the queue
:param wait_url_method: HTTP method for wait_url GET/POST
"""
GET = 'GET'
POST = 'POST'
def __init__(self, name, **kwargs):
super(Enqueue, self).__init__(**kwargs)
self.body = name
class Leave(Verb):
"""Signals the call to leave its queue
"""
GET = 'GET'
POST = 'POST'
class Record(Verb):
"""Record audio from caller
:param action: submit the result of the dial to this URL
:param method: submit to 'action' url using GET or POST
:param maxLength: maximum number of seconds to record
:param timeout: seconds of silence before considering the recording done
"""
GET = 'GET'
POST = 'POST'