def handle(text, mic, profile): """ Reports the current date based on the user's timezone. Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ tz = getTimezone(profile) now = datetime.datetime.now(tz=tz) # service = DateService() # response = service.convertTime(now) day = now.day month = now.month year = now.year if month == 1: smonth = "January" elif month == 2: smonth = "February" elif month == 3: smonth = "March" elif month == 4: smonth = "April" elif month == 5: smonth = "May" elif month == 6: smonth = "June" elif month == 7: smonth = "July" elif month == 8: smonth = "August" elif month == 9: smonth = "September" elif month == 10: smonth = "October" elif month == 11: smonth = "November" elif month == 12: smonth = "December" else: smonth = "e" mic.say("Today is %s of %s of %s ." % (day, smonth, year) )
def handle(text, mic, profile): tz = getTimezone(profile) now = datetime.datetime.now(tz=tz) service = DateService() response = service.convertTime(now) mic.say("It is %s right now." % response)
def handle(text, mic, profile): tz = getTimezone(profile) now = datetime.datetime.now(tz=tz) service = DateService() response = service.convertTime(now) root = Tk() root.wm_title("Mirror") w, h = root.winfo_screenwidth(), root.winfo_screenheight() root.overrideredirect(1) root.geometry("%dx%d+0+0" % (w, h)) root.focus_set() root.bind("1", root.quit()) root.config(background="#000000") mainFrame = Frame(root, width=w, height=h) mainFrame.grid(row=0, column=0, padx=10, pady=2) mainFrame.config(background="#000000") customFont = tkFont.Font(family="Helvetica", size=60) timeVar = StringVar() timeVar.set(response) weatherVar = StringVar() weatherVar.set("76°") timeLabel = Label(mainFrame, textvariable=timeVar, font=customFont, fg="white", bg="black") weatherLabel = Label(mainFrame, textvariable=weatherVar, font=customFont, fg="white", bg="black") timeLabel.place(relx=1, x=-2, y=2, anchor=NE) weatherLabel.place(relx=0, x=-2, y=2, anchor=NW) root.mainloop()
def getEventsTomorrow(profile, mic): # Time Delta function for adding one day one_day = datetime.timedelta(days=1) tz = getTimezone(profile) # Gets tomorrows Start and End Time in RFC3339 Format d = datetime.datetime.now(tz=tz) + one_day utcString = d.isoformat() m = re.search('([0-9]{2}\:[0-9]{2})', str(utcString)) #in form 2017-03-15T02:15:35.836202 utcString = m.group(0) tomorrowStartTime = str(d.strftime("%Y-%m-%d")) + "T00:00:00Z" tomorrowEndTime = str(d.strftime("%Y-%m-%d")) + "T23:59:59Z" page_token = None while True: # Gets events from primary calender from each page in tomorrow day boundaries events = service.events().list(calendarId='primary', pageToken=page_token, timeMin=tomorrowStartTime, timeMax=tomorrowEndTime).execute() if (len(events['items']) == 0): mic.say("You have no events scheduled Tomorrow") return for event in events['items']: try: eventTitle = event['summary'] eventTitle = str(eventTitle) eventRawStartTime = event['start'] eventRawStartTime = eventRawStartTime['dateTime'].split("T") temp = eventRawStartTime[1] startHour, startMinute, temp = temp.split(":", 2) startHour = int(startHour) appendingTime = "am" if ((startHour - 12) > 0): startHour = startHour - 12 appendingTime = "pm" startMinute = str(startMinute) startHour = str(startHour) mic.say(eventTitle + " at " + startHour + ":" + startMinute + " " + appendingTime) # This will be mic.say except KeyError, e: mic.say("Check Calender that you added it correctly") page_token = events.get('nextPageToken') if not page_token: return
def timeWakeUp(profile, mic): '''Returns (maybe says) the time to wake up.''' one_day = datetime.timedelta(days=1) try: tz = getTimezone(profile) except: None #If it isnt before 5am check tomorrow, otherwise check later today if not datetime.datetime.now().time().hour > 7: d = datetime.datetime.now(tz=tz) + one_day else: d = datetime.datetime.now(tz=tz) utcString = d.isoformat() m = re.search('([0-9]{2}\:[0-9]{2})', str(utcString)) utcString = m.group(0) tomorrowStartTime = str(d.strftime("%Y-%m-%d")) + "T00:00:00Z" tomorrowEndTime = str(d.strftime("%Y-%m-%d")) + "T23:59:59Z" page_token = None while True: events = service.events().list(calendarId='primary', pageToken=page_token, timeMin=tomorrowStartTime, timeMax=tomorrowEndTime).execute() if (len(events['items']) == 0): mic.say( "You have no events scheduled Tomorrow, so get up whenever you like!" ) return False event = events['items'][0] #first event of the day try: eventTitle = event['summary'] eventTitle = str(eventTitle) eventRawStartTime0 = event['start']['dateTime'] eventRawStartTime = eventRawStartTime0.split("T") temp = eventRawStartTime[1] startHour, startMinute, temp = temp.split(":", 2) startHour = int(startHour) startMinute = str(startMinute) startHour = str(startHour) mic.say("You need to be up for " + startHour + ":" + startMinute + " for " + eventTitle) return eventRawStartTime0 except KeyError, e: mic.say( "I got an error fetching data from the calander. Sorry Toby.") page_token = events.get('nextPageToken') if not page_token: return
def getEventsTomorrow(profile, mic): # Time Delta function for adding one day one_day = datetime.timedelta(days=1) tz = getTimezone(profile) # Gets tomorrows Start and End Time in RFC3339 Format d = datetime.datetime.now(tz=tz) + one_day utcString = d.isoformat() m = re.search('((\+|\-)[0-9]{2}\:[0-9]{2})', str(utcString)) utcString = m.group(0) tomorrowStartTime = str(d.strftime("%Y-%m-%d")) + "T00:00:00" + utcString tomorrowEndTime = str(d.strftime("%Y-%m-%d")) + "T23:59:59" + utcString page_token = None while True: # Gets events from primary calender from each page in tomorrow day boundaries events = service.events().list(calendarId='primary', pageToken=page_token, timeMin=tomorrowStartTime, timeMax=tomorrowEndTime).execute() if(len(events['items']) == 0): mic.say("You have no events scheduled Tomorrow") return for event in events['items']: try: eventTitle = event['summary'] eventTitle = str(eventTitle) eventRawStartTime = event['start'] eventRawStartTime = eventRawStartTime['dateTime'].split("T") temp = eventRawStartTime[1] startHour, startMinute, temp = temp.split(":", 2) startHour = int(startHour) appendingTime = "am" if ((startHour - 12) > 0 ): startHour = startHour - 12 appendingTime = "pm" startMinute = str(startMinute) startHour = str(startHour) mic.say(eventTitle + " at " + startHour + ":" + startMinute + " " + appendingTime) # This will be mic.say except KeyError, e: mic.say("Check Calender that you added it correctly") page_token = events.get('nextPageToken') if not page_token: return
def getEventsOnNextDayOfWeek(profile, mic, dayOfWeekStr, service): tz = getTimezone(profile) d = datetime.datetime.now(tz=tz) dayOfWeek = list(calendar.day_name).index(dayOfWeekStr) if (dayOfWeek == d.weekday()): timediff = datetime.timedelta(days=7) elif (dayOfWeek <= d.weekday()): timediff = datetime.timedelta(days=(7 - dayOfWeek)) else: timediff = datetime.timedelta(days=(dayOfWeek - d.weekday())) getEventsOn(d + timediff, tz, mic, "next " + dayOfWeekStr, service)
def getEventsToday(profile, mic): tz = getTimezone(profile) # Get Present Start Time and End Time in RFC3339 Format d = datetime.datetime.now(tz=tz) utcString = d.isoformat() m = re.search('((\+|\-)[0-9]{2}\:[0-9]{2})', str(utcString)) utcString = str(m.group(0)) todayStartTime = str(d.strftime("%Y-%m-%d")) + "T00:00:00" + utcString todayEndTime = str(d.strftime("%Y-%m-%d")) + "T23:59:59" + utcString page_token = None while True: # Gets events from primary calender from each page in present day boundaries events = service.events().list(calendarId='primary', pageToken=page_token, timeMin=todayStartTime, timeMax=todayEndTime).execute() if (len(events['items']) == 0): mic.say("You have no events scheduled for today") return for event in events['items']: try: eventTitle = event['summary'] eventTitle = str(eventTitle) eventRawStartTime = event['start'] eventRawStartTime = eventRawStartTime['dateTime'].split("T") temp = eventRawStartTime[1] startHour, startMinute, temp = temp.split(":", 2) startHour = int(startHour) appendingTime = "am" if ((startHour - 12) > 0): startHour = startHour - 12 appendingTime = "pm" startMinute = str(startMinute) startHour = str(startHour) mic.say(eventTitle + " at " + startHour + ":" + startMinute + " " + appendingTime) # This will be mic.say except KeyError, e: mic.say("Check Calender that you added it correctly") page_token = events.get('nextPageToken') if not page_token: return
def addEvent(profile, mic, service): while True: try: mic.say("What would you like to add?") eventData = mic.activeListen() createdEvent = service.events().quickAdd(calendarId='primary', text=eventData).execute() mic.say( "Added event " + createdEvent['summary'] + " on " + getReadableDateFromEvent(createdEvent, getTimezone(profile)) + " " + getReadableTimeFromEvent(createdEvent, getTimezone(profile))) # Create a variable for POST ev = createdEvent['summary'] dt = getReadableDateFromEvent(createdEvent, getTimezone(profile)) tm = getReadableTimeFromEvent(createdEvent, getTimezone(profile)) mic.say("Is this what you wanted?") if bool(re.search(r'\bYes\b', mic.activeListen(), re.IGNORECASE)): mic.say("Okay, it's on your calendar") # POST request for req here payload = {'user_id': 3, 'event': ev, 'date': dt, 'time': tm} r = requests.post( "http://178.128.62.29/api/schedule/createNew", params=payload) else: mic.say("My mistake, english is my second language.") service.events().delete(calendarId='primary', eventId=createdEvent['id']).execute() return except KeyError: mic.say( "Could not add event to your calender; check if internet issue." ) mic.say("Would you like to attempt again?") responseRedo = mic.activeListen() if bool(re.search(r'\bNo\b', responseRedo, re.IGNORECASE)): return
def getEventsBySummary( profile, mic, keyWords, service ): tz = getTimezone(profile) today = getStartOfDay(datetime.datetime.now(tz=tz)) oneMonthFromToday = today + relativedelta(months=1) events = queryEvents(convertDateToGoogleStr(tz, today), convertDateToGoogleStr(tz, oneMonthFromToday), service, keyWords) if len(events) == 0: mic.say("You don't have any events like that") return sep="" for event in events: eventTitle = getSummaryFromEvent(event) mic.say( sep + " on " + getReadableDateFromEvent(event, tz) + " " + eventTitle + getReadableTimeFromEvent(event, tz) ) sep="and"
def handle(text, speaker, requester, profile): """ Responds to user-input, typically speech text, by listing the user's Facebook friends with birthdays today. Arguments: text -- user-input, typically transcribed speech speaker -- used to interact with the user (output) requester -- used to interact with the user (input) profile -- contains information related to the user (e.g., phone number) """ oauth_access_token = profile['keys']["FB_TOKEN"] graph = facebook.GraphAPI(oauth_access_token) try: results = graph.request("me/friends", args={'fields': 'id,name,birthday'}) except facebook.GraphAPIError: speaker.clean_and_say("I have not been authorized to query your Facebook. If you " + "would like to check birthdays in the future, please visit " + "the Jasper dashboard.") return except: speaker.clean_and_say( "I apologize, there's a problem with that service at the moment.") return needle = datetime.datetime.now(tz=getTimezone(profile)).strftime("%m/%d") people = [] for person in results['data']: try: if needle in person['birthday']: people.append(person['name']) except: continue if len(people) > 0: if len(people) == 1: output = people[0] + " has a birthday today." else: output = "Your friends with birthdays today are " + \ ", ".join(people[:-1]) + " and " + people[-1] + "." else: output = "None of your friends have birthdays today." speaker.clean_and_say(output)
def handle(text, mic, profile): """ Responds to user-input, typically speech text, by listing the user's Facebook friends with birthdays today. Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ oauth_access_token = profile['keys']["FB_TOKEN"] graph = facebook.GraphAPI(oauth_access_token) try: results = graph.request("me/friends", args={'fields': 'id,name,birthday'}) except facebook.GraphAPIError: mic.say("I have not been authorized to query your Facebook. If you " + "would like to check birthdays in the future, please visit " + "the Jasper dashboard.") return except: mic.say( "I apologize, there's a problem with that service at the moment.") return needle = datetime.datetime.now(tz=getTimezone(profile)).strftime("%m/%d") people = [] for person in results['data']: try: if needle in person['birthday']: people.append(person['name']) except: continue if len(people) > 0: if len(people) == 1: output = people[0] + " has a birthday today." else: output = "Your friends with birthdays today are " + \ ", ".join(people[:-1]) + " and " + people[-1] + "." else: output = "None of your friends have birthdays today." mic.say(output)
def handle(text, mic, profile, bot=None): """ Reports the current time based on the user's timezone. Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ tz = getTimezone(profile) now = datetime.datetime.now(tz=tz) service = DateService() response = service.convertTime(now) mic.say("It is %s right now." % response)
def handle(text, mic, profile): """ Reports the current time based on the user's timezone. Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ tz = getTimezone(profile) now = datetime.datetime.now(tz=tz) service = DateService() response = service.convertTime(now) mic.say("Il est %s" % response)
def handle(text, speaker, requester, profile): """ Reports the current time based on the user's timezone. Arguments: text -- user-input, typically transcribed speech speaker -- used to interact with the user (output) requester -- used to interact with the user (input) profile -- contains information related to the user (e.g., phone number) """ tz = getTimezone(profile) now = datetime.datetime.now(tz=tz) service = DateService() response = service.convertTime(now) speaker.clean_and_say("It is %s right now." % response)
def task(self): self.tz = getTimezone(self.profile) self.now = datetime.datetime.now(tz=self.tz) self.service = DateService() self.response = self.service.convertTime(self.now) self.timeVar.set(self.response) self.numFiles = len([name for name in os.listdir(self.directory) if os.path.isfile(os.path.join(self.directory, name))]) if self.numFiles > self.numFileHolder: self.showPicture() print ("OLD: " + str(self.numFileHolder) + "NEW: " + str(self.numFiles)) self.numFileHolder = self.numFiles self.forecast = None if 'wmo_id' in self.profile: self.forecast = get_forcast_by_wmo_id(str(self.profile['wmo_id'])) elif 'location' in self.profile: self.forecast = get_forecast_by_name(str(self.profile['location'])) self.temp = self.forecast[0]['summary_detail']['value'][13:17] + unichr(176) self.weatherVar.set(self.temp) self.root.after(2000, self.task)
def handle(text, mic, profile): """ Reports the current time based on the user's timezone. Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ tz = getTimezone(profile) now = datetime.datetime.now(tz=tz) service = DateService() response = service.convertTime(now) d = datetime.datetime.strptime(response, "%I:%M %p") response = d.strftime("%H:%M") response = re.sub(r'00:', 'minuit ', response) response = re.sub(r'12:', 'midi ', response) mic.say("Il est %s." % response)
def handle(text, mic, profile): """ Reports the current date based on the user's location. Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ tz = getTimezone(profile) now = datetime.datetime.now(tz=tz) service = DateService() response = service.convertTime(now) day = (time.strftime("%A")) month = (time.strftime("%B")) num_day = (time.strftime("%d")) message = "It is " + day + "the " + num_day + "today, get over karishma" mic.say(message)
def handle(text, mic, profile, wxbot=None): """ Reports the current time based on the user's timezone. Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) wxBot -- wechat robot """ tz = getTimezone(profile) now = datetime.datetime.now(tz=tz) service = DateService() response = service.convertTime(now) if "AM" in response: response = u"上午" + response.replace("AM", "") elif "PM" in response: response = u"下午" + response.replace("PM", "") mic.say(u"现在时间是 %s " % response)
def handle(text, mic, profile): """ Reports the current time based on the user's timezone. Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ tz = getTimezone(profile) now = datetime.datetime.now(tz=tz) service = DateService() response = service.convertTime(now) comment = '' print("Current hour is " + str(now.hour)) if now.hour > 19: comment = ' It is time to be sleeping.' mic.say("It is {0} right now. {1}".format(response, comment) )
def handle(self, text, mic, profile): """ Reports the current time based on the user's timezone. Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ tz = getTimezone(profile) now = datetime.datetime.now(tz=tz) service = DateService() response = service.convertTime(now) self.blittxt(response, 150, white, black) mic.say("It is %s right now master." % response) time.sleep(1)
def handle(text, speaker, requester, profile): """ Responds to user-input, typically speech text, with a summary of the relevant weather for the requested date (typically, weather information will not be available for days beyond tomorrow). Arguments: text -- user-input, typically transcribed speech speaker -- used to interact with the user (output) requester -- used to interact with the user (input) profile -- contains information related to the user (e.g., phone number) """ forecast = None if 'wmo_id' in profile: forecast = get_forecast_by_wmo_id(str(profile['wmo_id'])) elif 'location' in profile: forecast = get_forecast_by_name(str(profile['location'])) if not forecast: speaker.clean_and_say("I'm sorry, I can't seem to access that information. Please " + "make sure that you've set your location on the dashboard.") return tz = getTimezone(profile) service = DateService(tz=tz) date = service.extractDay(text) if not date: date = datetime.datetime.now(tz=tz) weekday = service.__daysOfWeek__[date.weekday()] if date.weekday() == datetime.datetime.now(tz=tz).weekday(): date_keyword = "Today" elif date.weekday() == ( datetime.datetime.now(tz=tz).weekday() + 1) % 7: date_keyword = "Tomorrow" else: date_keyword = "On " + weekday output = None for entry in forecast: try: date_desc = entry['title'].split()[0].strip().lower() if date_desc == 'forecast': # For global forecasts date_desc = entry['title'].split()[2].strip().lower() weather_desc = entry['summary'] elif date_desc == 'current': # For first item of global forecasts continue else: # US forecasts weather_desc = entry['summary'].split('-')[1] if weekday == date_desc: output = date_keyword + \ ", the weather will be " + weather_desc + "." break except: continue if output: output = replaceAcronyms(output) speaker.clean_and_say(output) else: speaker.clean_and_say( "I'm sorry. I can't see that far ahead.")
def handle(self, text, mic, profile): """ Reports the current time based on the user's timezone. Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ mic.say("clock mode on") done = False while done == False: t = (time.strftime("%m/%d/%Y")) a, b, c = t.split('/') if a == '01': a = 'January' if a == '02': a = 'February' if a == '03': a = 'March' if a == '04': a = 'April' if a == '05': a = 'May' if a == '06': a = 'June' if a == '07': a = 'July' if a == '08': a = 'August' if a == '09': a = 'September' if a == '10': a = 'October' if a == '11': a = 'November' if a == '12': a = 'December' d, e = b if d == '0': b = e date = ('%s %s %s' % (a, b, c)) self.background.fill(black) for event in pygame.event.get(): if event.type == pygame.QUIT: done = True if event.type == pygame.MOUSEBUTTONDOWN: done = True tz = getTimezone(profile) now = datetime.datetime.now(tz=tz) service = DateService() response = service.convertTime(now) self.pygm.blitjtxt(response, 150, 0, 240, 160, white) self.pygm.blitjtxt(date, 40, 0, 240, 220, white) pygame.display.flip() time.sleep(1)
def handle(text, mic, profile): """ Responds to user-input, typically speech text, with a summary of the relevant weather for the requested date (typically, weather information will not be available for days beyond tomorrow). Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ forecast = None if 'wmo_id' in profile: forecast = get_forecast_by_wmo_id(str(profile['wmo_id'])) elif 'location' in profile: forecast = get_forecast_by_name(str(profile['location'])) if not forecast: mic.say("I'm sorry, I can't seem to access that information. Please " + "make sure that you've set your location on the dashboard.") return tz = getTimezone(profile) service = DateService(tz=tz) date = service.extractDay(text) if not date: date = datetime.datetime.now(tz=tz) weekday = service.__daysOfWeek__[date.weekday()] if date.weekday() == datetime.datetime.now(tz=tz).weekday(): date_keyword = "Today" elif date.weekday() == (datetime.datetime.now(tz=tz).weekday() + 1) % 7: date_keyword = "Tomorrow" else: date_keyword = "On " + weekday output = None for entry in forecast: try: date_desc = entry['title'].split()[0].strip().lower() if date_desc == 'forecast': # For global forecasts date_desc = entry['title'].split()[2].strip().lower() weather_desc = entry['summary'] elif date_desc == 'current': # For first item of global forecasts continue else: # US forecasts weather_desc = entry['summary'].split('-')[1] if weekday == date_desc: output = date_keyword + \ ", the weather will be " + weather_desc + "." break except: continue if output: output = replaceAcronyms(output) mic.say(output) else: mic.say("I'm sorry. I can't see that far ahead.")
def handle(text, mic, profile): """ Responds to user-input, typically speech text, with a summary of the relevant weather for the requested date (typically, weather information will not be available for days beyond tomorrow). Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ logger = logging.getLogger(__name__) logger.debug(text) logger.debug("location=" + str(profile['location'])) forecast = None if 'location' in profile: forecast = get_forecast_by_name(str(profile['location'])) if not forecast: mic.say( "I'm sorry, I can't seem to access weather information right now.") # mic.say("Please make sure that you've set your location on the dashboard.") return # tz = getTimezone(profile) # logger.debug(tz) date_keyword = 'all' for word in text.split(): logger.debug('word=' + word) if word != "WEATHER" and word in WORDS: date_keyword = word.lower() matchThese = [] tz = getTimezone(profile) service = DateService(tz=tz) today_wkday = datetime.datetime.now(tz=tz).weekday() today = service.__daysOfWeek__[today_wkday] if date_keyword == 'tomorrow': tomorrow_wkday = (today_wkday + 1) % 7 date_keyword = service.__daysOfWeek__[tomorrow_wkday] logger.debug("date_keyword=" + date_keyword) if date_keyword != '': matchThese.append(date_keyword) if date_keyword == 'today': matchThese.append('current') matchThese.append('rest') matchThese.append('this') # matchThese.append('tonight') for entry in matchThese: logger.debug('match=' + entry) for entry in forecast: date_desc = entry['title'].split()[0].strip().lower() logger.debug('[' + date_desc + ']: title=' + str(entry['title'])) # logger.debug(forecast) for entry in forecast: sayThis = '' date_desc = entry['title'].split()[0].strip().lower() if (date_desc in matchThese) or (date_keyword == 'all'): if date_desc == 'current': sayThis = str(entry['title']) else: sayThis = str(entry['summary']) if sayThis != '': mic.say(sayThis) return
def handle(text, mic, profile): """ Responds to user-input, typically speech text, with a summary of the relevant weather for the requested date (typically, weather information will not be available for days beyond tomorrow). Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ logger = logging.getLogger(__name__) forecast = None if 'wmo_id' in profile: forecast = get_forecast_by_wmo_id(str(profile['wmo_id'])) elif 'location' in profile: forecast = get_forecast_by_name(str(profile['location'])) if not forecast: mic.say("Oups, je ne peux pas acceder à vos informations. Vérifier que vous avez bien renseigné votre localisation.") return tz = getTimezone(profile) now = datetime.datetime.now(tz=tz) extract = extractDate(text, now) if not extract: weekday = extractDate("Aujourd'hui", now)['weekday'] date = now else: weekday = extract['weekday'] date = extract['date'] if date.weekday() == now.weekday(): date_keyword = "Aujourd'hui" elif date.weekday() == (now.weekday() + 1) % 7: date_keyword = "Demain" else: date_keyword = weekday output = None for entry in forecast: #try: date_desc = entry['title'].split()[0].strip().lower() if date_desc == u'prévisions': # For global forecasts date_desc = entry['title'].split()[3].strip().lower() weather_desc = entry['summary'] logger.debug("PREVISIONS : " + date_desc + " " + weather_desc) elif date_desc == u'conditions': # For first item of global forecasts logger.debug("CONDITIONS") continue else: # US forecasts weather_desc = entry['summary'].split('-')[1] logger.debug("OTHER : " + weather_desc) logger.debug("EGALITE ? " + weekday + " et " + date_desc.title()) if weekday == date_desc.title(): output = u"Les prévisions pour " + date_keyword + u" sont : " + weather_desc + "." break #except: #continue if output: output = replaceAcronyms(output) mic.say(output) else: mic.say( "Désolé, j'ai eu un problème.")
def getEventsToday(profile, mic, service): tz = getTimezone(profile) d = datetime.datetime.now(tz=tz) getEventsOn(d, tz, mic, "today", service)
def handle(text, mic, profile): """ Responds to user-input, typically speech text, with a summary of the relevant weather for the requested date (typically, weather information will not be available for days beyond tomorrow). Arguments: text -- user-input, typically transcribed speech mic -- used to interact with the user (for both input and output) profile -- contains information related to the user (e.g., phone number) """ logger = logging.getLogger(__name__) forecast = None if 'wmo_id' in profile: forecast = get_forecast_by_wmo_id(str(profile['wmo_id'])) elif 'location' in profile: forecast = get_forecast_by_name(str(profile['location'])) if not forecast: mic.say( "Oups, je ne peux pas acceder à vos informations. Vérifier que vous avez bien renseigné votre localisation." ) return tz = getTimezone(profile) now = datetime.datetime.now(tz=tz) extract = extractDate(text, now) if not extract: weekday = extractDate("Aujourd'hui", now)['weekday'] date = now else: weekday = extract['weekday'] date = extract['date'] if date.weekday() == now.weekday(): date_keyword = "Aujourd'hui" elif date.weekday() == (now.weekday() + 1) % 7: date_keyword = "Demain" else: date_keyword = weekday output = None for entry in forecast: #try: date_desc = entry['title'].split()[0].strip().lower() if date_desc == u'prévisions': # For global forecasts date_desc = entry['title'].split()[3].strip().lower() weather_desc = entry['summary'] logger.debug("PREVISIONS : " + date_desc + " " + weather_desc) elif date_desc == u'conditions': # For first item of global forecasts logger.debug("CONDITIONS") continue else: # US forecasts weather_desc = entry['summary'].split('-')[1] logger.debug("OTHER : " + weather_desc) logger.debug("EGALITE ? " + weekday + " et " + date_desc.title()) if weekday == date_desc.title(): output = u"Les prévisions pour " + date_keyword + u" sont : " + weather_desc + "." break #except: #continue if output: output = replaceAcronyms(output) mic.say(output) else: mic.say("Désolé, j'ai eu un problème.")
def getEventsTomorrow(profile, mic, service): tz = getTimezone(profile) d = datetime.datetime.now(tz=tz) + datetime.timedelta(days=1) getEventsOn(d, tz, mic, "tomorrow", service)