本文整理汇总了Python中siriObjects.uiObjects.AddViews类的典型用法代码示例。如果您正苦于以下问题:Python AddViews类的具体用法?Python AddViews怎么用?Python AddViews使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了AddViews类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: resumeTimer
def resumeTimer(self, speech, language):
response = self.getResponseForRequest(TimerGet(self.refId))
timer_properties = response["properties"]["timer"]["properties"]
timer = TimerObject(timerValue=timer_properties["timerValue"], state=timer_properties["state"])
if timer.state == "Paused":
response = self.getResponseForRequest(TimerResume(self.refId))
if response["class"] == "ResumeCompleted":
view = AddViews(self.refId, dialogPhase="Completion")
view1 = AssistantUtteranceView(
speakableText=timerPlugin.localizations["Timer"]["timerWasResumed"][language],
dialogIdentifier="Timer#timerWasResumed",
)
view2 = TimerSnippet(timers=[timer])
view.views = [view1, view2]
self.sendRequestWithoutAnswer(view)
self.complete_request()
else:
view = AddViews(self.refId, dialogPhase="Completion")
view1 = AssistantUtteranceView(
speakableText=timerPlugin.localizations["Timer"]["timerIsAlreadyStopped"][language],
dialogIdentifier="Timer#timerIsAlreadyStopped",
)
view2 = TimerSnippet(timers=[timer])
view.views = [view1, view2]
self.sendRequestWithoutAnswer(view)
self.complete_request()
开发者ID:michael9559,项目名称:SiriServerPlugins,代码行数:28,代码来源:__init__.py
示例2: facebookName
def facebookName(self, speech, language):
if (language == "de-DE"):
def getFBPicture():
fbconsole.AUTH_SCOPE = ['publish_stream', 'publish_checkins', 'read_stream', 'offline_access']
fbconsole.authenticate()
file = urllib2.urlopen('https://graph.facebook.com/%s?access_token=%s&fields=picture' % (fbconsole.get('/me')['id'], fbconsole.ACCESS_TOKEN))
data = json.load(file)
return data["picture"]
self.say("Ich checke ...")
view = AddViews(self.refId, dialogPhase="Completion")
AnswerString =""
AnswerString = u"Du heißt: " + fbconsole.get('/me')['name']
AnswerString = AnswerString + "\nDu bist: " + fbconsole.get('/me')['gender']
AnswerString = AnswerString + "\nDeine Sprache : " + fbconsole.get('/me')['locale']
AnswerString = AnswerString + "\nDeine Uhrzeit ist : " + fbconsole.get('/me')['updated_time']
FacebookImage = AnswerObject(title="Profile photo",lines=[AnswerObjectLine(image=getFBPicture())])
FacebookInfo = AnswerObject(title='Your info',lines=[AnswerObjectLine(text=AnswerString)])
view1 = 0
view1 = AnswerSnippet(answers=[FacebookImage, FacebookInfo])
view.views = [view1]
self.say("Hier ist deine Info :")
self.sendRequestWithoutAnswer(view)
self.complete_request()
开发者ID:tb78,项目名称:SiriServer,代码行数:27,代码来源:facebook.py
示例3: whereAmI
def whereAmI(self, speech, language):
location = self.getCurrentLocation(force_reload=True,accuracy=GetRequestOrigin.desiredAccuracyBest)
url = "http://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&sensor=false&language={2}".format(str(location.latitude),str(location.longitude), language)
try:
jsonString = urllib2.urlopen(url, timeout=3).read()
except:
pass
if jsonString != None:
response = json.loads(jsonString)
if response['status'] == 'OK':
components = response['results'][0]['address_components']
street = filter(lambda x: True if "route" in x['types'] else False, components)[0]['long_name']
stateLong= filter(lambda x: True if "administrative_area_level_1" in x['types'] or "country" in x['types'] else False, components)[0]['long_name']
try:
postalCode= filter(lambda x: True if "postal_code" in x['types'] else False, components)[0]['long_name']
except:
postalCode=""
try:
city = filter(lambda x: True if "locality" in x['types'] or "administrative_area_level_1" in x['types'] else False, components)[0]['long_name']
except:
city=""
countryCode = filter(lambda x: True if "country" in x['types'] else False, components)[0]['short_name']
view = AddViews(self.refId, dialogPhase="Completion")
if language == "de-DE":
the_header="Dein Standort"
elif language == 'fr-FR':
the_header="Votre position"
else:
#self.say("This is your location {0}".format(self.user_name()))
the_header="This is your location {0}".format(self.user_name())
view = AddViews(self.refId, dialogPhase="Completion")
mapsnippet = MapItemSnippet(items=[MapItem(label=postalCode+" "+city, street=street, city=city, postalCode=postalCode, latitude=location.latitude, longitude=location.longitude, detailType="CURRENT_LOCATION")])
view.views = [AssistantUtteranceView(speakableText=the_header, dialogIdentifier="Map#whereAmI"), mapsnippet]
self.sendRequestWithoutAnswer(view)
self.complete_request()
开发者ID:castvoid,项目名称:SiriServerCore,代码行数:35,代码来源:__init__.py
示例4: displaypicture
def displaypicture(self, speech, language, regex):
if (language == "en-US"):
if (speech.find(u'顯示照片') == 0):
speech = speech.replace(u'顯示照片',' ',1)
elif (speech.find(u"顯示圖片") == 0):
speech = speech.replace(u"圖片",' ',1)
elif (speech.find(u"搜尋照片") == 0):
speech = speech.replace(u"搜尋照片",' ',1)
elif (speech.find(u"搜尋圖片") == 0):
speech = speech.replace(u"搜尋圖片",' ',1)
speech = speech.strip()
if speech == "":
speech = self.ask(u"你想搜尋什麼的圖片?")
Query = urllib.quote_plus(speech.encode("utf-8"))
SearchURL = u'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&imgsz=small|medium|large|xlarge&q=' + str(Query)
try:
if language == 'en-US':
self.say(u"這是 "+speech+u" 的圖片...")
jsonResponse = urllib2.urlopen(SearchURL).read()
jsonDecoded = json.JSONDecoder().decode(jsonResponse)
ImageURL = jsonDecoded['responseData']['results'][0]['unescapedUrl']
view = AddViews(self.refId, dialogPhase="Completion")
ImageAnswer = AnswerObject(title=speech,lines=[AnswerObjectLine(image=ImageURL)])
view1 = AnswerSnippet(answers=[ImageAnswer])
view.views = [view1]
self.sendRequestWithoutAnswer(view)
self.complete_request()
except (urllib2.URLError):
self.say("Sorry, a connection to Google Images could not be established.")
self.complete_request()
开发者ID:ialnevets,项目名称:SiriServerCoreTW,代码行数:35,代码来源:__init__.py
示例5: quakesearch
def quakesearch(self, speech, language, regex):
searchString = regex.group(regex.lastindex).strip()
gefunden = 0
html = urllib.urlopen("http://www.emsc-csem.org/service/rss/rss.php?typ=emsc").read()
dom = xml.dom.minidom.parseString(html)
self.say("Überprüfung meiner Quellen...")
for node in dom.getElementsByTagName("item"):
sendtitle = node.getElementsByTagName("title")
sendtime = node.getElementsByTagName("emsc:time")
sendlat = node.getElementsByTagName("geo:lat")
sendlong = node.getElementsByTagName("geo:long")
sendmag = node.getElementsByTagName("emsc:magnitude")
sendeinfo = sendtitle[0].firstChild.data + "\n" + sendtime[0].firstChild.data
if re.match(".*" + searchString + ".*", sendeinfo, re.IGNORECASE):
gefunden = 1
# self.say(sendeinfo, (' '))
view = AddViews(self.refId, dialogPhase="Completion")
the_header = "Epicenter: " + sendtitle[0].firstChild.data
Location = SiriLocation(
the_header, "", "", "", "", "", sendlat[0].firstChild.data, sendlong[0].firstChild.data
)
mapsnippet = SiriMapItemSnippet(items=[SiriMapItem(the_header, Location)])
view.views = [AssistantUtteranceView(text=sendeinfo, dialogIdentifier="Map"), mapsnippet]
self.sendRequestWithoutAnswer(view)
if gefunden == 0:
self.say(u'Sorry, ich fand keine Erdbeben fuer "' + searchString + '"')
self.complete_request()
开发者ID:sullenlook,项目名称:plugins,代码行数:27,代码来源:__init__.py
示例6: webcam
def webcam(self, speech, language):
URL = ''
Title = speech.replace ('How does it look in ', '')
print Title
if Title == "austin":
URL = u'http://12.52.91.101/jpg/image.jpg'
elif Title == "yosemite":
URL = u'http://maps.ca.water.usgs.gov/webcams/happyisles-latest.jpg'
elif Title == "fort collins":
URL = u'http://www.co.larimer.co.us/webcam/old_courthouse.jpg'
elif Title == "boulder":
URL = u'http://www.esrl.noaa.gov/gsd/webcam/flatiron.jpg'
elif Title == "san francisco":
URL = u'http://hd-sf.com/images/livedata/480-live.jpg'
elif Title == "lake travis":
URL = u'http://media.lintvnews.com/BTI/KXAN02.jpg'
view = AddViews(self.refId, dialogPhase="Completion")
ImageAnswer = AnswerObject(title=str(Title),lines=[AnswerObjectLine(image=URL)])
view1 = AnswerSnippet(answers=[ImageAnswer])
view.views = [view1]
self.sendRequestWithoutAnswer(view)
self.complete_request()
开发者ID:iron85,项目名称:SiriServerCore,代码行数:30,代码来源:webcams.py
示例7: imdb_info
def imdb_info(self, speech, language, regex):
ShowTitle = regex.group(regex.lastindex)
Query = urllib.quote_plus(ShowTitle.encode("utf-8"))
IMDBURL = 'http://www.imdbapi.com/?i=&t=%s' % (str(Query))
try:
# Query IMDB
jsonResponse = urllib2.urlopen(IMDBURL).read()
jsonDecoded = json.JSONDecoder().decode(jsonResponse)
if language == 'id-ID':
self.say("Berikut adalah info tentang film tersebut:")
view = AddViews(self.refId, dialogPhase="Completion")
else:
self.say("Here is the info about the movie:")
view = AddViews(self.refId, dialogPhase="Completion")
AnswerString = jsonDecoded['Title'] + ' (' + jsonDecoded['Released'] + ')' + '\n Genre: ' + jsonDecoded['Genre'] + '\n Directors: ' + jsonDecoded['Director'] + '\n Actors: ' + jsonDecoded['Actors'] + '\n Plot: ' + jsonDecoded['Plot'] + '\n Runtime: ' + jsonDecoded['Runtime'] + '\n Rating: ' + jsonDecoded['Rating'] + ' / Voted: ' + jsonDecoded['Votes'] + 'x'
IMDBAnswerMissed = AnswerObject(title='IMDB:',lines=[AnswerObjectLine(text=AnswerString)])
view1 = 0
view1 = AnswerSnippet(answers=[IMDBAnswerMissed])
view.views = [view1]
self.sendRequestWithoutAnswer(view)
self.complete_request()
except (urllib2.URLError):
if language == 'id-ID':
self.say("Maaf, koneksi ke IMDBapi tidak dapat dilakukan.")
else:
self.say("Sorry, a connection to IMDBapi could not be established.")
self.complete_request()
开发者ID:iPhoneV8,项目名称:SiriServerCore,代码行数:30,代码来源:__init__.py
示例8: sb_newshows
def sb_newshows(self, speech, language):
SickBeardURL = u'http://%s:%s/api/%s/?cmd=future&sort=date&type=today|missed|soon' % (IPAddress, Port, APIKey)
try:
# Query SickBeard for new / missed shows
jsonResponse = urllib2.urlopen(SickBeardURL).read()
jsonDecoded = json.JSONDecoder().decode(jsonResponse)
self.say("Here is a list of new shows this week:")
view = AddViews(self.refId, dialogPhase="Completion")
AnswerString = ''
# Get missed shows -
for show in jsonDecoded['data']['missed']:
AnswerString = AnswerString + show['airs'] + ': ' + show['show_name'] + '\n'
SickBeardAnswerMissed = AnswerObject(title='Missed Shows:',lines=[AnswerObjectLine(text=AnswerString)])
# Get shows airing today
AnswerString = ''
for show in jsonDecoded['data']['today']:
AnswerString = AnswerString + show['airs'] + ': ' + show['show_name'] + '\n'
SickBeardAnswerToday = AnswerObject(title='Airing Today:',lines=[AnswerObjectLine(text=AnswerString)])
# Get shows airing soon
for show in jsonDecoded['data']['soon']:
AnswerString = AnswerString + show['airs'] + ': ' + show['show_name'] + '\n'
SickBeardAnswerUpcoming = AnswerObject(title='Upcoming Shows:',lines=[AnswerObjectLine(text=AnswerString)])
view1 = 0
view1 = AnswerSnippet(answers=[SickBeardAnswerMissed, SickBeardAnswerUpcoming])
view.views = [view1]
self.sendRequestWithoutAnswer(view)
self.complete_request()
except (urllib2.URLError):
self.say("Sorry, a connection to SickBeard could not be established.")
self.complete_request()
开发者ID:Nurfballs,项目名称:SiriServer-SickBeard,代码行数:35,代码来源:sickbeard.py
示例9: whereis
def whereis(self, speech, language, regex):
self.say('Searching...',' ')
Title = regex.group(regex.lastindex).strip()
Query = urllib.quote_plus(str(Title.encode("utf-8")))
googleurl = "http://maps.googleapis.com/maps/api/geocode/json?address={0}&sensor=true&language=en".format(Query)
jsonString = urllib2.urlopen(googleurl, timeout=20).read()
response = json.loads(jsonString)
if (response['status'] == 'OK') and (len(response['results'])):
googleplaces_results = []
for result in response['results']:
label = "{0}".format(Title.title())
street =result['formatted_address']
latitude=result['geometry']['location']['lat']
longitude=result['geometry']['location']['lng']
mapitem = MapItem(label=label, street=street, latitude=latitude, longitude=longitude)
googleplaces_results.append(mapitem)
mapsnippet = MapItemSnippet(items=googleplaces_results)
view = AddViews(self.refId, dialogPhase="Completion")
view.views = [AssistantUtteranceView(speakableText='Showing {0} on the map...'.format(Title.title()), dialogIdentifier="googlePlacesMap"), mapsnippet]
self.sendRequestWithoutAnswer(view)
self.complete_request()
else:
self.say("Sorry, I couldn't find that location...")
self.complete_request()
开发者ID:iron85,项目名称:SiriServerCore,代码行数:25,代码来源:__init__.py
示例10: authtest
def authtest(self, speech, language, regex):
if self.assistant_id() == "[6CF4E775-2DB0-4C99-A5D8-DB1B35EEDE00":
self.say("Zugelassen!")
else:
self.say("Netter Versuch, Newfag...","Netter Versuch Newfag.")
ans = self.ask(u" ▲\n▲ ▲","Ich wette, Du schaffst es nicht").lower()
if ans != "op ist eine Schwuchtel" and ans != "new fag" and ans != "newfag":
view = AddViews(self.refId, dialogPhase="Completion")
ImageAnswer = AnswerObject(title=str("Trolololololololololololololololololololololololololololol"),lines=[AnswerObjectLine(image="http://harryj.co.uk/t.gif")])
view1 = AnswerSnippet(answers=[ImageAnswer])
view.views = [view1]
self.sendRequestWithoutAnswer(view)
answer = None
filename = "./plugins/priv/cat.txt"
file = open(filename, 'r')
file_size = os.stat(filename)[6]
while answer != "Yes" and answer != "Yeah":
lnum = random.randint(0, file_size-1)
file.seek((file.tell()+lnum)%file_size)
file.readline()
line=file.readline()
self.say("Cat fact number "+str(lnum)+":\n"+str(line).rstrip('\n'))
answer = self.ask("Did you know that?")
view = AddViews(self.refId, dialogPhase="Completion")
ImageAnswer = AnswerObject(title=str(""),lines=[AnswerObjectLine(image="http://harryj.co.uk/b.gif")])
view1 = AnswerSnippet(answers=[ImageAnswer])
view.views = [view1]
self.sendRequestWithoutAnswer(view)
self.complete_request()
开发者ID:sullenlook,项目名称:fragmichwas,代码行数:29,代码来源:__init__.py
示例11: displaypicture
def displaypicture(self, speech, language, regex):
if language == "zh-CN":
Title = regex.group(3).strip()
else:
Title = regex.group(regex.lastindex).strip()
Query = urllib.quote_plus(Title.encode("utf-8"))
SearchURL = u'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&imgsz=small|medium|large|xlarge&q=' + str(Query)
try:
if language == "zh-CN":
self.say(u"这是有关"+str(Title.encode("utf-8"))+"的图片:")
else:
self.say("Here is the image for "+Title+"...")
jsonResponse = urllib2.urlopen(SearchURL).read()
jsonDecoded = json.JSONDecoder().decode(jsonResponse)
ImageURL = jsonDecoded['responseData']['results'][0]['unescapedUrl']
view = AddViews(self.refId, dialogPhase="Completion")
ImageAnswer = AnswerObject(title=Title,lines=[AnswerObjectLine(image=ImageURL)])
view1 = AnswerSnippet(answers=[ImageAnswer])
view.views = [view1]
self.sendRequestWithoutAnswer(view)
self.complete_request()
except (urllib2.URLError):
if language == "zh-CN":
self.say(u"抱歉,我无法连接谷歌图片服务。")
else:
self.say("Sorry, a connection to Google Images could not be established.")
self.complete_request()
开发者ID:jonesgithub,项目名称:SiriServer,代码行数:27,代码来源:displaypicture.py
示例12: newsFeed
def newsFeed(self, speech, language):
statuses = 15 #how many statuses you want to fetch
limit = 0
error = 0
if (language == "de-DE"):
statusString = ""
view = AddViews(self.refId, dialogPhase="Completion")
self.say("Ich checke ...")
for post in fbconsole.iter_pages(fbconsole.get('/me/home')):
if(error == 1):
error = 0
else :
limit = limit + 1
try:
post['message']
ansewer = post['from']['name'] + " schrieb : " + post['message']
print "INFO Getting status : ", limit
statusString = statusString + ansewer + "\n\n"
#self.say(ansewer)
except KeyError as (strerror):
#print "Key error({0})".format(strerror)
error = 1
continue
if(limit == statuses):
break
facebookStatuses = AnswerObject(title='Statuses :',lines=[AnswerObjectLine(text=statusString)])
view1 = 0
view1 = AnswerSnippet(answers=[facebookStatuses])
view.views = [view1]
self.sendRequestWithoutAnswer(view)
self.complete_request()
开发者ID:tb78,项目名称:SiriServer,代码行数:33,代码来源:facebook.py
示例13: quakesearch
def quakesearch(self, speech, language, regex):
searchString = regex.group(regex.lastindex).strip()
gefunden = 0;
html = urllib.urlopen("http://www.emsc-csem.org/service/rss/rss.php?typ=emsc").read()
dom = xml.dom.minidom.parseString(html)
self.say("Checking my sources...")
for node in dom.getElementsByTagName('item'):
sendtitle = node.getElementsByTagName('title')
sendtime = node.getElementsByTagName('emsc:time')
sendlat = node.getElementsByTagName('geo:lat')
sendlong = node.getElementsByTagName('geo:long')
sendmag = node.getElementsByTagName('emsc:magnitude')
sendeinfo = sendtitle[0].firstChild.data + '\n' + sendtime[0].firstChild.data
if re.match(".*"+searchString+".*", sendeinfo, re.IGNORECASE):
gefunden = 1;
# self.say(sendeinfo, (' '))
view = AddViews(self.refId, dialogPhase="Completion")
the_header = "Epicenter: " + sendtitle[0].firstChild.data
Location=SiriLocation(the_header,"","","","","",sendlat[0].firstChild.data,sendlong[0].firstChild.data)
mapsnippet = SiriMapItemSnippet(items=[SiriMapItem(the_header, Location)])
view.views = [AssistantUtteranceView(text=sendeinfo, dialogIdentifier="Map"), mapsnippet]
self.sendRequestWithoutAnswer(view)
if gefunden == 0:
self.say(u"Sorry I did not find any earthquake for \""+searchString+"\"")
self.complete_request()
开发者ID:iPhoneV8,项目名称:SiriServerCore,代码行数:25,代码来源:__init__.py
示例14: call
def call(self, phone, person, language):
if phone == None:
print "abandon"
self.complete_request()
return
root = ResultCallback(commands=[])
rootView = AddViews("", temporary=False, dialogPhase="Completion", views=[])
root.commands.append(rootView)
rootView.views.append(AssistantUtteranceView(text=responses['callPerson'][language].format(person.fullName, numberTypesLocalized[phone.label][language], phone.number), speakableText=responses['callPersonSpeak'][language].format(person.fullName, numberTypesLocalized[phone.label][language]), dialogIdentifier="PhoneCall#initiatePhoneCall", listenAfterSpeaking=False))
rootView.callbacks = []
# create some infos of the target
personAttribute=PersonAttribute(data=phone.number, displayText=person.fullName, obj=Person())
personAttribute.object.identifer = person.identifier
call = PhoneCall("", recipient=phone.number, faceTime=False, callRecipient=personAttribute)
rootView.callbacks.append(ResultCallback(commands=[call]))
call.callbacks = []
# now fill in error messages (airplanemode, no service, invalidNumber, fatal)
for i in range(4):
errorRoot = AddViews(None, temporary=False, dialogPhase="Completion", scrollToTop=False, views=[])
errorRoot.views.append(AssistantUtteranceView(text=errorOnCallResponse[language][i]['text'], speakableText=errorOnCallResponse[language][i]['text'], dialogIdentifier=errorOnCallResponse[language][i]['dialogIdentifier'], listenAfterSpeaking=False))
call.callbacks.append(ResultCallback(commands=[errorRoot], code=errorOnCallResponse[language][i]['code']))
self.complete_request([root])
开发者ID:hajimela,项目名称:SiriServer,代码行数:28,代码来源:phonecalls.py
示例15: currentTime
def currentTime(self, speech, language):
# first tell that we look it up
view = AddViews(self.refId, dialogPhase="Reflection")
view.views = [
AssistantUtteranceView(
text=timePlugin.localizations["currentTime"]["search"][language],
speakableText=timePlugin.localizations["currentTime"]["search"][language],
dialogIdentifier="Clock#getTime",
)
]
self.sendRequestWithoutAnswer(view)
# tell him to show the current time
view = AddViews(self.refId, dialogPhase="Summary")
view1 = AssistantUtteranceView(
text=timePlugin.localizations["currentTime"]["currentTime"][language],
speakableText=timePlugin.localizations["currentTime"]["currentTime"][language],
dialogIdentifier="Clock#showTimeInCurrentLocation",
)
clock = ClockObject()
clock.timezoneId = self.connection.assistant.timeZoneId
view2 = ClockSnippet(clocks=[clock])
view.views = [view1, view2]
self.sendRequestWithoutAnswer(view)
self.complete_request()
开发者ID:413x,项目名称:SiriServer,代码行数:25,代码来源:timePlugin.py
示例16: moviecover
def moviecover(self, speech, language, regex):
query = regex.group(regex.lastindex).strip()
search = self.res["search_cover"][language]
self.say(search.format(query))
infos = self.searchMovie(query, language)
ImageURL = None
if infos != None:
try:
here = self.res["here_cover"][language]
self.say(here.format(infos["title"]))
ImageURL = infos["cover url"]
except:
no = self.res["no_cover"][language]
self.say(no.format(infos["title"]))
if ImageURL != None:
ImageUrlBig = imdb.helpers.fullSizeCoverURL(infos)
if ImageUrlBig != None:
ImageURL = ImageUrlBig
view = AddViews(self.refId, dialogPhase="Completion")
ImageAnswer = AnswerObject(title=infos["title"], lines=[AnswerObjectLine(image=ImageURL)])
view1 = AnswerSnippet(answers=[ImageAnswer])
view.views = [view1]
self.sendRequestWithoutAnswer(view)
self.complete_request()
开发者ID:bexel,项目名称:SiriServer,代码行数:28,代码来源:imdbPlugin.py
示例17: do_webrequest
def do_webrequest(self, speech, language):
# Edit this adress.
pireLocation = 'http://dib.li/siri/response.php'
location = self.getCurrentLocation(force_reload=True)
postdata = {
'text': speech.replace("Test", "", 1),
'language': language,
'latitude': str( location.latitude ),
'longitude': str( location.longitude ),
'timezone': self.assistant.timeZoneId,
'region': self.assistant.region
};
req = urllib2.Request( pireLocation + "?" + urllib.urlencode( postdata ),
headers = {
"Content-Type": "application/json",
"Accept": "*/*",
"User-Agent": "pire-plugin",
})
webjson = urllib2.urlopen(req).read()
request = json.loads(webjson)
view = AddViews(self.refId, dialogPhase="Summary")
view.views = request
print view.to_plist()
self.sendRequestWithoutAnswer(view.to_plist())
self.complete_request()
开发者ID:Chr0meCoda,项目名称:Siri-Command-Manager,代码行数:30,代码来源:webservice.py
示例18: setAlarm
def setAlarm(self, speech, language):
alarmString = re.match(alarmPlugin.res["setAlarm"][language], speech, re.IGNORECASE)
alarmHour = int(alarmString.group("t1"))
alarm24Hour = alarmHour
alarmMinutes = alarmString.group("t2")
alarmAMPM = alarmString.group("am")
alarmLabelExists = alarmString.group("name")
# check if we are naming the alarm
if alarmLabelExists == None:
alarmLabel = None
else:
alarmLabel = alarmString.group(5)
# the siri alarm object requires 24 hour clock
if alarmAMPM == "pm" and alarmHour != 12:
alarm24Hour += 12
if alarmMinutes == None:
alarmMinutes = "00"
else:
alarmMinutes = int(alarmMinutes.strip())
view = AddViews(self.refId, dialogPhase="Reflection")
view.views = [
AssistantUtteranceView(
speakableText=alarmPlugin.localizations["Alarm"]["settingAlarm"][language],
dialogIdentifier="Alarm#settingAlarm",
)
]
self.sendRequestWithoutAnswer(view)
# create the alarm
alarm = AlarmObject(alarmLabel, int(alarmMinutes), alarm24Hour, None, 1)
response = self.getResponseForRequest(AlarmCreate(self.refId, alarm))
print(alarmPlugin.localizations["Alarm"]["alarmWasSet"][language].format(alarmHour, alarmMinutes, alarmAMPM))
view = AddViews(self.refId, dialogPhase="Completion")
if alarmLabel == None:
view1 = AssistantUtteranceView(
speakableText=alarmPlugin.localizations["Alarm"]["alarmWasSet"][language].format(
alarmHour, alarmMinutes, alarmAMPM
),
dialogIdentifier="Alarm#alarmWasSet",
)
else:
view1 = AssistantUtteranceView(
speakableText=alarmPlugin.localizations["Alarm"]["alarmSetWithLabel"][language].format(
alarmLabelExists, alarmLabel, alarmHour, alarmMinutes, alarmAMPM
),
dialogIdentifier="Alarm#alarmSetWithLabel",
)
view2 = AlarmSnippet(alarms=[alarm])
view.views = [view1, view2]
self.sendRequestWithoutAnswer(view)
self.complete_request()
开发者ID:castvoid,项目名称:SiriServerCore,代码行数:59,代码来源:__init__.py
示例19: whereAmI
def whereAmI(self, speech, language):
location = self.getCurrentLocation(force_reload=True,accuracy=GetRequestOrigin.desiredAccuracyBest)
url = "http://maps.googleapis.com/maps/api/geocode/json?latlng={0},{1}&sensor=false&language={2}".format(str(location.latitude),str(location.longitude), language)
try:
jsonString = urllib2.urlopen(url, timeout=10).read()
except:
pass
if jsonString != None:
response = json.loads(jsonString)
if response['status'] == 'OK':
components = response['results'][0]['address_components']
street = filter(lambda x: True if "route" in x['types'] else False, components)[0]['long_name']
stateLong= filter(lambda x: True if "administrative_area_level_1" in x['types'] or "country" in x['types'] else False, components)[0]['long_name']
try:
postalCode= filter(lambda x: True if "postal_code" in x['types'] else False, components)[0]['long_name']
except:
postalCode=""
try:
city = filter(lambda x: True if "locality" in x['types'] or "administrative_area_level_1" in x['types'] else False, components)[0]['long_name']
except:
city=""
countryCode = filter(lambda x: True if "country" in x['types'] else False, components)[0]['short_name']
view = AddViews(self.refId, dialogPhase="Completion")
if language == "de-DE":
the_header="Dein Standort"
elif language == 'fr-FR':
the_header="Votre position"
elif language == 'zh-CN':
self.say(u"这是您的位置 {0}:".format(self.user_name()))
the_header=u"您的位置"
else:
self.say("This is your location {0}".format(self.user_name()))
the_header="Your location"
view = AddViews(self.refId, dialogPhase="Completion")
print location.latitude
print location.longitude
print countryCode
mapsnippet = MapItemSnippet(items=[MapItem(label=postalCode+" "+city, street=street, city=city, countryCode=countryCode, postalCode=postalCode, latitude=location.latitude, longitude=location.longitude, detailType="CURRENT_LOCATION")])
view.views = [AssistantUtteranceView(text=the_header, dialogIdentifier="Map#whereAmI"), mapsnippet]
self.sendRequestWithoutAnswer(view)
else:
if language=="de-DE":
self.say('Die Googlemaps informationen waren ungenügend!','Fehler')
elif language == 'fr-FR':
self.say(u"La réponse de Googlemaps ne contient pas l'information nécessaire",'Erreur')
elif language == 'zh-CN':
self.say(u"我找不到您的位置。")
else:
self.say('The Googlemaps response did not hold the information i need!','Error')
else:
if language=="de-DE":
self.say('Ich konnte keine Verbindung zu Googlemaps aufbauen','Fehler')
if language=="fr-FR":
self.say(u"Je ne peux pas établir de connexion à Googlemaps",'Erreur')
if language=="zh-CN":
self.say(u"我无法访问谷歌地图。")
else:
self.say('Could not establish a conenction to Googlemaps','Error');
self.complete_request()
开发者ID:dschu-lab,项目名称:SiriServerCore,代码行数:59,代码来源:__init__.py
示例20: googleplaces_search
def googleplaces_search(self, speech, language, regex):
#added
global Title
#end addition
if language == "fr-FR":
self.say('Je recherche...',' ')
else:
self.say('Searching...',' ')
mapGetLocation = self.getCurrentLocation()
latitude= mapGetLocation.latitude
longitude= mapGetLocation.longitude
#modified
if Title == None:
Title = regex.group(regex.lastindex).strip()
Query = urllib.quote_plus(str(Title.encode("utf-8")))
else:
Query = urllib.quote_plus(Title)
#end modify
random_results = random.randint(2,15)
googleurl = "https://maps.googleapis.com/maps/api/place/search/json?location={0},{1}&radius=5000&name={2}&sensor=true&key={3}".format(latitude,longitude,str(Query),str(googleplaces_api_key))
try:
jsonString = urllib2.urlopen(googleurl, timeout=20).read()
except:
jsonString = None
if jsonString != None:
response = json.loads(jsonString)
if (response['status'] == 'OK') and (len(response['results'])):
googleplaces_results = []
for result in response['results']:
if "rating" in result:
avg_rating = result["rating"]
else:
avg_rating = 0.0
rating = Rating(value=avg_rating, providerId='Google Places', count=0)
details = Business(totalNumberOfReviews=0,name=result['name'],rating=rating)
if (len(googleplaces_results) < random_results):
mapitem = MapItem(label=result['name'], street=result['vicinity'], latitude=result['geometry']['location']['lat'], longitude=result['geometry']['location']['lng'])
mapitem.detail = details
googleplaces_results.append(mapitem)
else:
break
mapsnippet = MapItemSnippet(items=googleplaces_results)
count_min = min(len(response['results']),random_results)
count_max = max(len(response['results']),random_results)
view = AddViews(self.refId, dialogPhase="Completion")
view.views = [AssistantUtteranceView(speakableText='I found '+str(count_max)+' '+str(Title)+' results... '+str(count_min)+' of them are fairly close to you:', dialogIdentifier="googlePlacesMap"), mapsnippet]
self.sendRequestWithoutAnswer(view)
else:
if language == "fr-FR":
self.say("Je suis désolé, je n'ai pas trouvé de résultats pour "+str(Title)+" près de vous!")
else:
self.say("I'm sorry but I did not find any results for "+str(Title)+" near you!")
else:
if language == "fr-FR":
self.say("Je suis désolé, je n'ai pas trouvé de résultats pour "+str(Title)+" près de vous!")
else:
self.say("I'm sorry but I did not find any results for "+str(Title)+" near you!")
self.complete_request()
开发者ID:Shrugs,项目名称:googlePlacesSearchCustom,代码行数:59,代码来源:__init__.py
注:本文中的siriObjects.uiObjects.AddViews类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大 |
请发表评论