-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
669 lines (598 loc) · 28.8 KB
/
__init__.py
File metadata and controls
669 lines (598 loc) · 28.8 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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This is a sms plugin for SiriServerCore
# created by Eichhoernchen
#
# This file is free for private use, you need a commercial license for paid servers
#
# It's distributed under the same license as SiriServerCore
#
# You can view the license here:
# https://github.com/Eichhoernchen/SiriServerCore/blob/master/LICENSE
#
# So if you have a SiriServerCore commercial license
# you are allowed to use this plugin commercially otherwise you are breaking the law
#
# This file can be freely modified, but this header must retain untouched
#
#
from plugin import *
from siriObjects.baseObjects import ObjectIsCommand
from siriObjects.contactObjects import PersonSearch, PersonSearchCompleted
from siriObjects.smsObjects import SmsSms, SmsSnippet
from siriObjects.systemObjects import SendCommands, StartRequest, \
PersonAttribute, Person, DomainObjectCreate, DomainObjectCreateCompleted, \
DomainObjectUpdate, DomainObjectUpdateCompleted, DomainObjectRetrieve, \
DomainObjectRetrieveCompleted, DomainObjectCommit, DomainObjectCommitCompleted, \
DomainObjectCancel, DomainObjectCancelCompleted, AcknowledgeAlert
from siriObjects.uiObjects import UIDisambiguationList, UIListItem, \
UIConfirmationOptions, ConfirmSnippet, UIConfirmSnippet, UICancelSnippet, \
AddViews, AssistantUtteranceView, UISayIt
import datetime
import random
#import pytz
responses = {
'notFound':
{
'de-DE': u"Entschuldigung, ich konnte niemanden in deinem Telefonbuch finden der so heißt",
'en-US': u"Sorry, I did not find a match in your phone book"
},
'devel':
{
'de-DE': u"Entschuldigung, aber diese Funktion befindet sich noch in der Entwicklungsphase",
'en-US': u"Sorry this feature is still under development"
},
'select':
{
'de-DE': u"Wen genau?",
'en-US': u"Which one?"
},
'selectNumber':
{
'de-DE': u"Welche Telefonnummer für {0}",
'en-US': u"Which phone one for {0}"
},
'mustRepeat':
{
'de-DE': [u"Entschuldigung ich hab dich leider nicht verstanden."],
'en-US': [u"Sorry, I did not understand, please try again", u"Sorry, I don't know what you want"]
},
'askForMessage':
{
'de-DE': [u"Was willst du schreiben?", u"Was soll drin stehen?", u"Du kannst mir jetzt diktieren!"],
'en-US': [u"What do you want to say?", u"What do you want to include in the message?", u"Please dictate me the contents!"]
},
'showUpdate':
{
'de-DE': [u"Ich hab deine Nachricht geschrieben. Willst du sie jetzt senden?", u"OK. Willst du die Nachricht jetzt senden?"],
'en-US': [u"I updated your message. Ready to send it?", u"Ok, I got that, do you want to send it?", u"Thanks, do you want to send it now?"]
},
'cancelSms':
{
'de-DE': [u"OK, I schick sie nicht.", u"OK, ich hab sie verworfen"],
'en-US': [u"OK, I won't send it.", u"OK, I deleted it."]
},
'cancelFail':
{
'de-DE': [u"Sorry, aber mir ist ein Fehler beim Abbrechen passiert"],
'en-US': [u"Sorry I could not properly cancel your message"]
},
'createSmsFail':
{
'de-DE': [u"Ich konnte keine neue Nachricht anlegen, sorry"],
'en-US': [u"I could not create a new message, sorry!"]
},
'updateSmsFail':
{
'de-DE': [u"Entschuldigung ich konnte die Nachricht nicht schreiben"],
'en-US': [u"Sorry, I could not update your message!"]
},
'sendSms':
{
'de-DE': [u"OK, ich verschicke die Nachricht"],
'en-US': [u"OK, I'll send your message."]
},
'sendSmsFail':
{
'de-DE': [u"Umpf da ist was schief gelaufen, sorry"],
'en-US': [u"Hm something gone wrong, I could not send the message, I'm very sorry"]
},
'clarification':
{
'de-DE': [u"Fortfahren mit senden, abbrechen, anschauen oder ändern."],
'en-US': [u"To continue, you can Send, Cancel, Review, or Change it."]
},
'haveNewMessages':
{
'en-US': [u"You have {0} new message{1}."],
},
'noNewMessages':
{
'en-US': [u"You don't have any new messages."],
}
}
questions = {
'answerSEND':
{
'de-DE': ['yes', 'senden'], # you must include yes
'en-US': ['yes', 'send']
},
'answerCANCEL':
{
'de-DE': ['cancel', 'abbrechen', 'stop', 'nein'], # you must include cancel
'en-US': ['cancel', 'no', 'abort']
},
'answerUPDATE':
{
'de-DE': ['ändern', 'verändern'],
'en-US': ['change', 'update']
},
'answerREVIEW':
{
'de-DE': ['anschauen', 'zeigen', 'zeig'],
'en-US': ['review', 'view']
}
}
responseRegex = {
"yes": {'en-US': ".*(yes|ya|yeah|yup|please|ok).*"},
"no": {'en-US': ".*(no|nope|negative|negatory).*"},
"read": {'en-US': ".*read.*"},
"reply": {'en-US': ".*reply.*"},
"cancel": {'en-US': ".*(cancel|neither|done).*"},
"next": {'en-US': ".*(next|continue).*"}
}
snippetButtons = {
'denyText':
{
'de-DE': "Cancel",
'en-US': "Cancel"
},
'cancelLabel':
{
'de-DE': "Cancel",
'en-US': "Cancel"
},
'submitLabel':
{
'de-DE': "Send",
'en-US': "Send"
},
'confirmText':
{
'de-DE': "Send",
'en-US': "Send"
},
'cancelTrigger':
{
'de-DE': "Deny",
'en-US': "Deny"
}
}
speakableDemitter={
'en-US': u", or ",
'de-DE': u', oder '}
errorNumberTypes= {
'de-DE': u"Ich habe dich nicht verstanden, versuch es bitte noch einmal.",
'en-US': u"Sorry, I did not understand, please try again."
}
errorNumberNotPresent= {
'de-DE': u"Ich habe diese {0} von {1} nicht, aber eine andere.",
'en-US': u"Sorry, I don't have a {0} number from {1}, but another."
}
numberTypesLocalized= {
'_$!<Mobile>!$_': {'en-US': u"mobile", 'de-DE': u"Handynummer"},
'iPhone': {'en-US': u"iPhone", 'de-DE': u"iPhone-Nummer"},
'_$!<Home>!$_': {'en-US': u"home", 'de-DE': u"Privatnummer"},
'_$!<Work>!$_': {'en-US': u"work", 'de-DE': u"Geschäftsnummer"},
'_$!<Main>!$_': {'en-US': u"main", 'de-DE': u"Hauptnummer"},
'_$!<HomeFAX>!$_': {'en-US': u"home fax", 'de-DE': u'private Faxnummer'},
'_$!<WorkFAX>!$_': {'en-US': u"work fax", 'de-DE': u"geschäftliche Faxnummer"},
'_$!<OtherFAX>!$_': {'en-US': u"_$!<OtherFAX>!$_", 'de-DE': u"_$!<OtherFAX>!$_"},
'_$!<Pager>!$_': {'en-US': u"pager", 'de-DE': u"Pagernummer"},
'_$!<Other>!$_':{'en-US': u"other phone", 'de-DE': u"anderes Telefon"}
}
namesToNumberTypes = {
'de-DE': {'mobile': "_$!<Mobile>!$_", 'handy': "_$!<Mobile>!$_", 'zuhause': "_$!<Home>!$_", 'privat': "_$!<Home>!$_", 'arbeit': "_$!<Work>!$_"},
'en-US': {'work': "_$!<Work>!$_",'home': "_$!<Home>!$_", 'mobile': "_$!<Mobile>!$_"}
}
class shortMessaging(Plugin):
def finalSend(self, sms, language):
commitCMD = DomainObjectCommit(self.refId)
commitCMD.identifier = SmsSms()
commitCMD.identifier.identifier = sms.identifier
answer = self.getResponseForRequest(commitCMD)
if ObjectIsCommand(answer, DomainObjectCommitCompleted):
answer = DomainObjectCommitCompleted(answer)
# update the sms object with current identifier and time stamp
sms.identifier = answer.identifier
# the timestamp should be timezone aware
# we could use the pytz lib for that
# get the timezone from the assistant
# and supply it to pytz which we can
# supply to now()
sms.dateSent = datetime.datetime.now()
# tell the user we sent the sms
createAnchor = UIAddViews(self.refId)
createAnchor.dialogPhase = createAnchor.DialogPhaseConfirmedValue
# create a view to ask for the message
askCreateView = UIAssistantUtteranceView()
askCreateView.dialogIdentifier = "CreateSms#sentSMS"
askCreateView.text = askCreateView.speakableText = random.choice(responses['sendSms'][language])
askCreateView.listenAfterSpeaking = False
snippet = SmsSnippet()
snippet.smss = [sms]
createAnchor.views = [askCreateView, snippet]
self.sendRequestWithoutAnswer(createAnchor)
else:
self.say(random.choice(responses['sendSmsFail'][language]))
def createSmsSnippet(self, sms, addConfirmationOptions, dialogIdentifier, text, language):
createAnchor = UIAddViews(self.refId)
createAnchor.dialogPhase = createAnchor.DialogPhaseConfirmationValue
# create a view to ask for the message
askCreateView = UIAssistantUtteranceView()
askCreateView.dialogIdentifier = dialogIdentifier
askCreateView.text = askCreateView.speakableText = text
askCreateView.listenAfterSpeaking = True
# create a snippet for the sms
snippet = SmsSnippet()
if addConfirmationOptions:
# create some confirmation options
conf = UIConfirmSnippet({})
conf.requestId = self.refId
confOpts = UIConfirmationOptions()
confOpts.submitCommands = [SendCommands([conf, StartRequest(False, "^smsConfirmation^=^yes^")])]
confOpts.confirmCommands = confOpts.submitCommands
cancel = UICancelSnippet({})
cancel.requestId = self.refId
confOpts.cancelCommands = [SendCommands([cancel, StartRequest(False, "^smsConfirmation^=^cancel^")])]
confOpts.denyCommands = confOpts.cancelCommands
confOpts.denyText = snippetButtons['denyText'][language]
confOpts.cancelLabel = snippetButtons['cancelLabel'][language]
confOpts.submitLabel = snippetButtons['submitLabel'][language]
confOpts.confirmText = snippetButtons['confirmText'][language]
confOpts.cancelTrigger = snippetButtons['cancelTrigger'][language]
snippet.confirmationOptions = confOpts
snippet.smss = [sms]
createAnchor.views = [askCreateView, snippet]
return createAnchor
def createNewMessage(self, phone, person):
# create a new domain object the sms...
x = SmsSms()
x.recipients = [phone.number]
msgRecipient = PersonAttribute()
msgRecipient.object = Person()
msgRecipient.object.identifier = person.identifier if hasattr(person, "identifier") else ""
msgRecipient.data = phone.number
msgRecipient.displayText = person.fullName if hasattr(person, "fullName") else phone.number
x.msgRecipients = [msgRecipient]
x.outgoing = True
answer = self.getResponseForRequest(DomainObjectCreate(self.refId, x))
if ObjectIsCommand(answer, DomainObjectCreateCompleted):
answer = DomainObjectCreateCompleted(answer)
x = SmsSms()
x.outgoing = True
x.identifier = answer.identifier
return x
else:
return None
def getSmssForIdentifier(self, identifier):
# fetch the current version
retrieveCMD = DomainObjectRetrieve(self.refId)
x = SmsSms()
x.identifier = identifier
retrieveCMD.identifiers = [x]
answer = self.getResponseForRequest(retrieveCMD)
if ObjectIsCommand(answer, DomainObjectRetrieveCompleted):
answer = DomainObjectRetrieveCompleted(answer)
if len(answer.objects) > 1:
self.logger.warning("I do not support multiple messages!")
result = SmsSms()
result.initializeFromPlist(answer.objects[0].to_plist())
return result
else:
return None
def askAndSetMessage(self, sms, language):
createAnchor = self.createSmsSnippet(sms, False, "CreateSms#smsMissingMessage", random.choice(responses['askForMessage'][language]), language)
smsText = self.getResponseForRequest(createAnchor)
# update the domain object
updateCMD = DomainObjectUpdate(self.refId)
updateCMD.identifier = sms
updateCMD.addFields = SmsSms()
updateCMD.setFields = SmsSms()
updateCMD.setFields.message = smsText
updateCMD.removeFields = SmsSms()
answer = self.getResponseForRequest(updateCMD)
if ObjectIsCommand(answer, DomainObjectUpdateCompleted):
return sms
else:
return None
def showUpdateAndAskToSend(self, sms, language):
createAnchor = self.createSmsSnippet(sms, True, "CreateSms#updatedMessageBody", random.choice(responses['showUpdate'][language]), language)
response = self.getResponseForRequest(createAnchor)
match = re.match("\^smsConfirmation\^=\^(?P<answer>.*)\^", response)
if match:
response = match.group('answer')
return response
def cancelSms(self, sms, language):
# cancel the sms
cancelCMD = DomainObjectCancel(self.refId)
cancelCMD.identifier = SmsSms()
cancelCMD.identifier.identifier = sms.identifier
answer = self.getResponseForRequest(cancelCMD)
if ObjectIsCommand(answer, DomainObjectCancelCompleted):
createAnchor = UIAddViews(self.refId)
createAnchor.dialogPhase = createAnchor.DialogPhaseCanceledValue
cancelView = UIAssistantUtteranceView()
cancelView.dialogIdentifier = "CreateSms#wontSendSms"
cancelView.text = cancelView.speakableText = random.choice(responses['cancelSms'][language])
createAnchor.views = [cancelView]
self.sendRequestWithoutAnswer(createAnchor)
self.complete_request()
else:
self.say(random.choice(responses['cancelFail'][language]))
self.complete_request()
def askForClarification(self, sms, language):
createAnchor = self.createSmsSnippet(sms, True, "CreateSms#notReadyToSendSms", random.choice(responses['clarification'][language]), language)
response = self.getResponseForRequest(createAnchor)
match = re.match("\^smsConfirmation\^=\^(?P<answer>.*)\^", response)
if match:
response = match.group('answer')
return response
def message(self, phone, person, language):
smsObj = self.createNewMessage(phone, person)
if smsObj == None:
self.say(random.choice(responses['createSmsFail'][language]))
self.complete_request()
return
smsObj = self.askAndSetMessage(smsObj, language)
if smsObj == None:
self.say(random.choice(responses['updateSmsFail'][language]))
self.complete_request()
return
satisfied = False
state = "SHOW"
# lets define a small state machine
while not satisfied:
smsObj = self.getSmssForIdentifier(smsObj.identifier)
if smsObj == None:
self.say(u"Sorry I lost your sms.")
self.complete_request()
return
if state == "SHOW":
instruction = self.showUpdateAndAskToSend(smsObj, language).strip().lower()
if any(k in instruction for k in (questions['answerSEND'][language])):
state = "SEND"
continue
if any(k in instruction for k in (questions['answerCANCEL'][language])):
state = "CLARIFY"
continue
self.say(random.choice(responses['mustRepeat'][language]))
continue
elif state == "WRITE":
smsObj = self.askAndSetMessage(smsObj, language)
if smsObj == None:
self.say(random.choice(responses['updateSmsFail'][language]))
self.complete_request()
return
state = "SHOW"
continue
elif state == "CLARIFY":
instruction = self.askForClarification(smsObj, language).strip().lower()
if any(k in instruction for k in (questions['answerSEND'][language])):
state = "SEND"
continue
if any(k in instruction for k in (questions['answerCANCEL'][language])):
state = "CANCEL"
continue
if any(k in instruction for k in (questions['answerUPDATE'][language])):
state = "WRITE"
continue
if any(k in instruction for k in (questions['answerREVIEW'][language])):
state = "SHOW"
continue
self.say(random.choice(responses['mustRepeat'][language]))
continue
elif state == "CANCEL":
self.cancelSms(smsObj, language)
satisfied = True
continue
elif state == "SEND":
self.finalSend(smsObj, language)
satisfied = True
continue
def searchUserByName(self, personToLookup):
search = PersonSearch(self.refId)
search.scope = PersonSearch.ScopeLocalValue
search.name = personToLookup
answerObj = self.getResponseForRequest(search)
if ObjectIsCommand(answerObj, PersonSearchCompleted):
answer = PersonSearchCompleted(answerObj)
return answer.results if answer.results != None else []
else:
raise StopPluginExecution("Unknown response: {0}".format(answerObj))
return []
def findPhoneForNumberType(self, person, numberType, language):
# first check if a specific number was already requested
phoneToMessage = None
if numberType != None:
# try to find the phone that fits the numberType
phoneToMessage = filter(lambda x: x.label == numberType, person.phones)
else:
favPhones = filter(lambda y: y.favoriteVoice if hasattr(y, "favoriteVoice") else False, person.phones)
if len(favPhones) == 1:
phoneToMessage = favPhones[0]
if phoneToMessage == None:
# lets check if there is more than one number
if len(person.phones) == 1:
if numberType != None:
self.say(errorNumberNotPresent.format(numberTypesLocalized[numberType][language], person.fullName))
phoneToMessage = person.phones[0]
else:
# damn we need to ask the user which one he wants...
while(phoneToMessage == None):
root = UIAddViews(self.refId)
root.dialogPhase = root.DialogPhaseClarificationValue
utterance = UIAssistantUtteranceView()
utterance.dialogIdentifier = "ContactDataResolutionDucs#foundAmbiguousPhoneNumberForContact"
utterance.speakableText = utterance.text = responses['selectNumber'][language].format(person.fullName)
utterance.listenAfterSpeaking = True
root.views = [utterance]
lst = UIDisambiguationList()
lst.items = []
lst.speakableSelectionResponse = "OK!"
lst.listenAfterSpeaking = True
lst.selectionResponse = "OK"
root.views.append(lst)
for phone in person.phones:
numberType = numberTypesLocalized[phone.label][language] if phone.label in numberTypesLocalized else phone.label
item = UIListItem()
item.title = ""
item.text = u"{0}: {1}".format(numberType, phone.number)
item.selectionText = item.text
item.speakableText = u"{0} ".format(numberType)
item.object = phone
item.commands = [SendCommands(commands=[StartRequest(handsFree=False, utterance=numberType)])]
lst.items.append(item)
answer = self.getResponseForRequest(root)
numberType = self.getNumberTypeForName(answer, language)
if numberType != None:
matches = filter(lambda x: x.label == numberType, person.phones)
if len(matches) == 1:
phoneToMessage = matches[0]
else:
self.say(errorNumberTypes[language])
else:
self.say(errorNumberTypes[language])
return phoneToMessage
def getNumberTypeForName(self, name, language):
# q&d
if name != None:
if name.lower() in namesToNumberTypes[language]:
return namesToNumberTypes[language][name.lower()]
else:
for key in numberTypesLocalized.keys():
if numberTypesLocalized[key][language].lower() == name.lower():
return numberTypesLocalized[key][language]
return name
def presentPossibleUsers(self, persons, language):
root = UIAddViews(self.refId)
root.dialogPhase = root.DialogPhaseClarificationValue
utterance = UIAssistantUtteranceView()
utterance.dialogIdentifier = "ContactDataResolutionDucs#disambiguateContact"
utterance.text = responses['select'][language]
utterance.speakableText = responses['select'][language]
utterance.listenAfterSpeaking = True
root.views = [utterance]
# create a list with all the possibilities
lst = UIDisambiguationList()
lst.items = []
lst.speakableSelectionResponse = "OK!"
lst.listenAfterSpeaking = True
lst.selectionResponse = "OK"
root.views.append(lst)
for person in persons:
item = UIListItem()
item.object = person
item.selectionResponse = person.fullName
item.selectionText = person.fullName
item.title = person.fullName
item.commands = [SendCommands([StartRequest(False, "^phoneCallContactId^=^urn:ace:{0}".format(person.identifier))])]
lst.items.append(item)
return root
@register("en-US", "(Write|Send)( a)?( new)? (message|sms) to (?P<recipient>[\w ]+?)$")
@register("de-DE", "(Sende|Schreib.)( eine)?( neue)? (Nachricht|sms) an (?P<recipient>[\w ]+?)$")
def sendSMS(self, speech, lang, regex):
recipient = regex.group('recipient')
possibleRecipients = self.searchUserByName(recipient)
personToMessage = None
if len(possibleRecipients) > 0:
if len(possibleRecipients) == 1:
personToMessage = possibleRecipients[0]
else:
identifierRegex = re.compile("\^phoneCallContactId\^=\^urn:ace:(?P<identifier>.*)")
# multiple users, ask user to select
while(personToMessage == None):
strUserToMessage = self.getResponseForRequest(self.presentPossibleUsers(possibleRecipients, lang))
self.logger.debug(strUserToMessage)
# maybe the user clicked...
identifier = identifierRegex.match(strUserToMessage)
if identifier:
strUserToMessage = identifier.group('identifier')
self.logger.debug(strUserToMessage)
for person in possibleRecipients:
if person.fullName == strUserToMessage or person.identifier == strUserToMessage:
personToMessage = person
if personToMessage == None:
# we obviously did not understand him.. but probably he refined his request... call again...
self.say(errorNumberTypes[lang])
if personToMessage != None:
self.message(self.findPhoneForNumberType(personToMessage, None, lang), personToMessage, lang)
self.say(responses['notFound'][lang])
self.complete_request()
#methods for message dictation
def readMessage(self, context):
#get sender from the AlertContext objects for the assistant
sender = context.msgSender.displayText
#send the a view with the name of the sender
summary = "New message from {0}:".format(sender)
views = AddViews(self.refId, temporary=False, dialogPhase="Summary", scrollToTop=False, views=[])
views.views.append(AssistantUtteranceView(text=summary, speakableText='', dialogIdentifier="FindSms#readThem"))
self.sendRequestWithoutAnswer(views)
#Send the SayIt command to the phone, so it will speak the contents of the message
sayIt = UISayIt(self.refId)
sayIt.context = context
sayIt.message = "New message from @{obj#sender} @{tts#\x1b\\pause=300\\\x1b\\rate=90\\}@{obj#subject}@{tts#\x1b\\pause=300\\\x1b\\rate=100\\} @{tts#\x1b\\pause=300\\\x1b\\rate=90\\}@{obj#message}@{tts#\x1b\\pause=300\\\x1b\\rate=100\\}"
self.send_object(sayIt)
def postMessageReadHandler(self, msgContext, language, nextMessage=False):
summary = u"You can \u2018Reply\u2019 or \u2018Read it\u2019 again."
views = AddViews(self.refId, temporary=False, dialogPhase="Summary", scrollToTop=False, views=[])
views.views.append(AssistantUtteranceView(text=summary, speakableText= "@{tts#\x1b\\pause=800\\}You can @{tts#\x1b\\pause=25\\}reply, or read it again.", listenAfterSpeaking=True, dialogIdentifier="FindSms#readingPostActions"))
resp = self.getResponseForRequest(views).encode('ascii')
read = re.compile(responseRegex['read'][language], re.IGNORECASE)
reply = re.compile(responseRegex['reply'][language], re.IGNORECASE)
cancel = re.compile(responseRegex['cancel'][language], re.IGNORECASE)
cont = re.compile(responseRegex['next'][language], re.IGNORECASE)
while (read.match(resp) == None) and (reply.match(resp) == None) and (cancel.match(resp) == None) and (cont.match(resp) == None):
self.say("I didn't get that, please try again.")
summary = u"You can \u2018Reply\u2019 or \u2018Read it\u2019 again."
views = AddViews(self.refId, temporary=False, dialogPhase="Summary", scrollToTop=False, views=[])
views.views.append(AssistantUtteranceView(text=summary, speakableText= "@{tts#\x1b\\pause=800\\}You can @{tts#\x1b\\pause=25\\}reply, or read it again.", listenAfterSpeaking=True, dialogIdentifier="FindSms#readingPostActions"))
resp = self.getResponseForRequest(views).encode('ascii')
if read.match(resp):
self.readMessage(msgContext)
self.postMessageReadHandler(msgContext, language, nextMessage)
elif reply.match(resp):
self.message(msgContext.msgSender.object.phones[0], msgContext.msgSender.object, language)
elif cancel.match(resp):
return 0;
elif nextMessage and cont.match(resp):
return 1;
@register("en-US", ".*(how|do I have|check my)( many| any)? (new )?messages.*")
def checkNewMessages(self, speech, langauge, regex):
if (hasattr(self.assistant, 'alerts') and (self.assistant.alerts != None)):
numNewMessages = len(self.assistant.alerts)
self.say(random.choice(responses['haveNewMessages'][langauge]).format(numNewMessages, "s" if numNewMessages>1 else ""))
else:
self.say(random.choice(responses['noNewMessages'][langauge]))
self.complete_request()
@register("en-US", ".*read( me)?( my)?( new)? (message|messages)")
def readNewMessgages(self, speech, langauge, regex):
if hasattr(self.assistant, 'alerts') and (self.assistant.alerts != None):
for context in self.assistant.alerts:
nextMessage = False
if len(self.assistant.alerts)>1 and context!=self.assistant.alerts[len(self.assistant.alerts)-1]:
nextMessage = True; #if this isn't the last new message waiting, we pass the postReadHandler this information, so it can allow the user to read next.
self.readMessage(context)
#Send the alert acknowledge command to the phone, so it will clear the alert flag for the message
alertAck = AcknowledgeAlert(self.refId)
alertAck.object = context
self.send_object(alertAck)
#ask the user what they want to do
cont = self.postMessageReadHandler(context, langauge, nextMessage)
if cont == 0:
self.complete_request();
return;
else:
self.say(random.choice(responses['noNewMessages'][langauge]))
self.complete_request()