def what_keyword(keyword="time"): ''' Return what <keyword> it is, e.g. time, day, etc. ''' keyword_map = { "time": "%I:%M%p", "day": "%A", "month": "%B", "year": "%Y", "date": "%A, %d %B %Y", } if keyword in DAYS: keyword = "day" elif keyword in MONTHS: keyword = "month" if keyword in keyword_map.keys(): answer = time.strftime(keyword_map[keyword]) if keyword == "time": answer = answer[1:] if answer.startswith("0") else answer answer = answer.lower() else: time_str = time.strftime("%I:%M%p").lower() ans = time_str[1:] if time_str.startswith("0") else time_str answer = time.strftime("%A, {}".format(ans)) paul.set_it(answer) return "It is {}.".format(answer)
def change_volume(keywords): """ Change the volume up or down, depending on the keywords """ code = "set volume output volume (output volume of (get volume settings) {} 6.25)" if paul.has_one_of(keywords, VERBS_UP + ["turn up", "adjust up", "louder"]): code = code.format("+") elif paul.has_one_of(keywords, VERBS_DOWN + ["turn down", "adjust down", "quieter"]): code = code.format("-") else: return "I'm not sure how you wanted me adjust the volume." paul.set_it(code) paul.run_script(code, language="applescript") return "Done!"
def scrape_first_paragraph(url): ''' Get the first paragraph of the specified (print-formatted) wikipedia article ''' gross_url = url.replace("/wiki/", "/w/index.php?title=")+"&printable=yes" paul.log("URL ATTEMPT: " + gross_url) d = paul.DOM.fromURL(gross_url) para = d["#mw-content-text"].get_immediate_child('p')[0].extract_raw_text() paul.set_it(url) para = stripIt(para) if para.endswith("may refer to:") or para.endswith("may refer to"): paul.open_URL(url) return "This is a diambiguation page. I'll bring it up now..." return para + "\n\n" + url
def change_brightness(keywords): """ Change the brightness up or down, depending on the keywords """ code = 'tell application "System Events" to key code {}' up = "113" down = "107" if paul.has_one_of(keywords, VERBS_UP + ["turn up", "adjust up", "brighter"]): code = code.format(up) elif paul.has_one_of(keywords, VERBS_DOWN + ["turn down", "adjust down", "dimmer"]): code = code.format(down) else: return "I can't tell how you wanted the brightness changed." paul.set_it(code) paul.run_script(code, language="applescript") return "Done!"
def find(params="", look_in=False): ''' Find the item that was searched for with necessary paramenters ''' home = look_in if look_in else "~" avoiders = [ "Library", "Cache", ".log", ".properties", ] command = 'mdfind -onlyin {}/ "{}"'.format(home.strip("\n"), params) results = paul.run_script(command, response=True).split("\n")[:-1] filtered_results = sorted([line.strip() for line in results if not has_one_of_substrings(line.strip(), avoiders)], key=len) paul.log("RESULTS FIRST 5: ", filtered_results[:10]) if len(filtered_results) > 0: if len(filtered_results) > 1: decision = choose(filtered_results[:5]) else: decision = filtered_results[0] paul.log("DECISION: " + str(decision)) it = paul.set_it(decision) paul.log('IT: {}'.format(it)) return decision else: return None
def findIt(what, sentence): ''' Get wikipedia's opening statement on the topic ''' url = ('http://en.wikipedia.org/wiki/{}'.format(re.sub(' ', '_', what))) try: result = scrape_first_paragraph(url) return result except urllib.error.HTTPError: if sentence.forward("discover"): return "I'll try something else, just a moment..." else: return "I found nothing!" except urllib.error.URLError: return "I couldn't complete the research for some reason. Are you connected to the internet?" except AttributeError: paul.set_it(url) paul.open_URL(url) return "I can't seem to read about this. Let me open it for you..."
def weather(day_index, sentence): ''' Simply get the weather for any day ''' if day_index > 5 or day_index < 0: return "I can't see that far ahead. Sorry!" try: page = urllib.request.urlopen("http://weather.yahooapis.com/" "forecastrss?u=" + paul.get_temp().lower() + "&w=" + paul.get_woeid()) except urllib.error.URLError: return ("I couldn't retrieve the weather. " + "Are you connected to the internet?") lines = page.readlines() conditions = get_conditions(lines, day_index) paul.log("WEATHER_RAW:", lines) paul.log("CONDITIONS:", conditions) paul.set_it("http://weather.yahoo.com/") if day_index == 0: condition = (", and {}".format(conditions['text'].lower()) if conditions['text'].lower() != "unknown" else "") temp = conditions['temp'] conditions2 = get_conditions(lines, 1) paul.log("CONDITIONS2:", conditions2) condition2 = conditions2['text'].lower() temp2 = "{}".format(conditions2['high']) com = comment(sentence, temp, conditions['text']) return "{0}It's {1}°{2}{3}. The high today is {4}°{2}, {5}.".format( com, temp, paul.get_temp(), condition, temp2, condition2) else: condition = conditions['text'].lower() com = comment(sentence, conditions['high'], conditions['text']) rep = ("{0}It will have a low of " "{1}°{2}, a high of {3}°{2}, and will be {4}.".format( com, conditions['low'], paul.get_temp(), conditions['high'], condition)) return rep
def process(sentence): ''' Process the sentence. ''' sentence.replace_it() eqns = make_equations(sentence) if len(eqns) == 0: return "I'm not sure what you want me try try and solve. Sorry!" subs = sentence.has_one_of(["sub", "substitute", "solve"]) rearrange = sentence.has_one_of(["rearrange", "solve"]) if subs: rearrange = False if (paul.get_it() and paul.Sentence(paul.get_it()).has_one_of("+/^*-=1234567890")): eqns.append(paul.get_it()) if len(eqns) < 2 else 0 paul.log(eqns) eqn_string = eqns[0] if subs: try: eqn_string = eqns[1] except IndexError: eqn_string = eqns[0] if rearrange: for e in eqns: if len(e) > 1: eqn_string = e break paul.log("SUBS:", subs, "REARRANGE:", rearrange) paul.log("EQUATION:", eqn_string) had_equals = True if not paul.has_word(eqn_string, "="): eqn_string = "y=" + eqn_string had_equals = False elif eqn_string.strip()[0] == "=": eqn_string = "y" + eqn_string paul.log("EQUATION:", eqn_string) # try: eqn = Equation(eqn_string) # except: # return "Something went horribly wrong when I tried to math. Oops." # if subs and len(eqns) > 1: eq2 = Equation(eqns[0]) if type(eq2.head.right.value) == float: eqn.substitute((eq2.head.left.value, eq2.head.right.value)) elif type(eqn.head.right.value) == float: eq2.substitute((eqn.head.left.value, eqn.head.right.value)) eqn, eq2 = eq2, eqn else: url = "http://www.wolframalpha.com/input/?i=" query = "sub {} into {}".format(eq2, eqn) query.replace("+", "%2D").replace("=", "%3D").replace("/", "%2F") paul.open_URL(url+query) return '''I was unsuccessful in finding the solution:\n{}\n{}'''.format(eq2, eqn) if rearrange: targ = "x" targets = sentence.keywords() for word, _ in targets: if len(word) == 1: targ = word try: eqn.rearrange_linear_for(targ) except RuntimeError: url = "http://www.wolframalpha.com/input/?i=" query = "rearrange {} for {}".format(eqn, targ) query.replace("+", "%2D").replace("=", "%3D").replace("/", "%2F") paul.open_URL(url+query) return "Oh dear, not a clue. Try this instead." result = str(eqn) if not had_equals: result = result[4:] paul.set_it(result) try: if result[0] == "(" and result[-1] == ")": result = result[1:-1] except IndexError: pass return result