def google(query): url = google_search(query + sites_query) if not url: return None match = re.match('(?:https?://)?xkcd.com/(\d+)/?', url) if match: return match.group(1)
async def on_message(message): user_id = message.author.id msg = message.content.lower() if message.author == client.user: return if msg.startswith('hi'): response = 'Hey' await message.channel.send(response) if msg.startswith('!google'): msg = msg.split(None, 1)[1] post_search_data(user_id, msg) response = google_search(msg, user_id) if response: response = 'Result of search: {}'.format(response) else: response = 'Your search - {} - did not match any documents.'.format( msg) await message.channel.send(response) if msg.startswith('!recent'): msg = msg.split(None, 1)[1] response = get_search_data(user_id, msg) if response: response = 'Result of search: {}'.format(response) else: response = 'Your search - {} - did not match any documents.'.format( msg) await message.channel.send(response)
def searchGoogle(startWords="try to find God"): results = search.google_search(startWords, my_api_key, my_cse_id, num=10) for result in results['items']: print(result["link"]) link = result["link"] #text = fetchtxt(link) #result['text'] = text #print(text[:100]) return results
def create_card_response(verb_noun_string, verb_list, noun_list, event_message, user_name): """Creates a card response based on the message sent in Hangouts Chat. """ question_from_user = event_message.encode('utf-8') parsed_key_words = verb_noun_string.encode('utf-8') pre_defined_question = check_pre_defined_questions(question_from_user, user_name, parsed_key_words) if pre_defined_question is not None: return pre_defined_question else: related_questions_list=[] related_questions_list, search_used, group = search.main(parsed_key_words, question_from_user) if (len(related_questions_list)==0): database_logger.logging_to_database(user_name, question_from_user,"NOT FOUND",parsed_key_words, "Null", "Null") return search.google_search(question_from_user) elif (len(related_questions_list)==1): for each_list in related_questions_list: question = each_list[0] index = each_list[1] theAnswer = search.getTheAns(index, None) database_logger.logging_to_database(user_name, question_from_user,related_questions_list,parsed_key_words, search_used, group) return theAnswer else: response = dict() cards = list() widgets = list() header = { 'header': { 'title': 'Answers for '+ question_from_user, 'subtitle': 'City of Edmonton chatbot', 'imageUrl': 'http://www.gwcl.ca/wp-content/uploads/2014/01/IMG_4371.png', 'imageStyle': 'IMAGE' } } cards.append(header) for each_list in related_questions_list: question = each_list[0] index = each_list[1] widgets.append( {'buttons': [{'textButton': {'text': question,'onClick': {'action': {'actionMethodName': INTERACTIVE_TEXT_BUTTON_ACTION,'parameters': [{'key': INTERACTIVE_BUTTON_PARAMETER_KEY,'value': index}]}}}}] }) cards.append({ 'sections': [{ 'widgets': widgets }]}) response['cards'] = cards database_logger.logging_to_database(user_name, question_from_user,related_questions_list,parsed_key_words, search_used, group) return response
def xkcd(jenni, input): # get latest comic for rand function and numeric input body = urllib2.urlopen("http://xkcd.com/rss.xml").readlines()[1] parsed = etree.fromstring(body) newest = etree.tostring(parsed.findall("channel/item/link")[0]) max_int = int(newest.split("/")[-3]) # if no input is given (pre - lior's edits code) if not input.group(2): # get rand comic random.seed() website = "http://xkcd.com/%d/" % random.randint(0,max_int+1) else: query = input.group(2).strip() # numeric input! get that comic number if it exists if (query.isdigit()): if (int(query) > max_int): jenni.say("Sorry, comic #" + query + " hasn't been posted yet. The last comic was #%d" % max_int) return else: website = "http://xkcd.com/" + query # non-numeric input! code lifted from search.g else: if (query.lower() == "latest" or query.lower() == "newest"): # special commands website = "https://xkcd.com/" else: # just google try: query = query.encode('utf-8') except: pass website = google_search("site:xkcd.com "+ query) chkForum = re.match(re.compile(r'.*?([0-9].*?):.*'), find_title(website)) # regex for comic specific forum threads if (chkForum): website = "http://xkcd.com/" + chkForum.groups()[0].lstrip('0') if website: # format and say result website += ' [' + find_title(website)[6:] + ']' jenni.say(website) elif website is False: jenni.say("Problem getting data from Google.") else: jenni.say("No results found for '%s'." % query)
def push_search(self): name = self.lineEdit.text() print name self.status_changed('Search...') db = search.load_db('mtbf.db') print 'db_load' t = '' url_new, comp_type, soup2 = search.find_type_on_newegg(name) t += '<p>' + 'Link to component on NewEgg:' + '</p>' t += '<a href="' + url_new + '">' + url_new + "</a>" t += '<p>' + "\n\nComponent name: " + name + '</p>' t += '<p>' + "\nComponent type: " + '</p>' default_mtbf, comp_type = search.find_default_mtbf(comp_type, soup2, db) t += ", ".join([str(x) for x in comp_type] ) self.status_changed('Search MTBF in Google...') extra_tag = '' num_page=2 if self.cb_mtbf.isChecked(): extra_tag += 'MTBF MTTF' if self.cb_fit.isChecked(): extra_tag += 'FIT failures in time' if self.cb_extra.isChecked(): extra_tag += self.lineEdit_2.text() s_e = str(self.comboBox.currentText()) if s_e == 'Google': num_page = 1 search_result = search.google_search(name, extra_tag, num_page) new_t = search.parse_mtbf(search_result) self.status_changed('Results:') print new_t t += new_t self.textBrowser.setText(t) self.mtbf_label.setText(default_mtbf)
def get_reply(message): message = message.lower() reply_text = "" if "google" in message: message = message.replace("google ", "") return search.google_search(message) elif "directions from" and "to" in message: removal_list = ["directions ", "from ", "to "] for word in removal_list: message = message.replace(word, "") message = message.split() origin = message[0] destination = message[1] return map.get_directions(origin, destination) elif "search" in message: message = message.replace("search ", "") return search.wiki_search(message) elif "find" in message: removal_list = ["find ", "meters ", "near "] for word in removal_list: message = message.replace(word, "") message = message.split() address = "{}%{}%{}".format(message[2], message[3], message[4]) return find.locations_around(address, message[1], message[0]) else: reply_text = "i can only google and provied direction as of right now" return reply_text
def search(term): try: import search except ImportError, e: print e return term if isinstance(term, unicode): term = term.encode('utf-8') else: term = term.decode('utf-8') term = term.replace('_', ' ') try: uri = search.google_search('site:en.wikipedia.org %s' % term) except IndexError: return term if uri: return uri[len('https://en.wikipedia.org/wiki/'):] else: return term def wikipedia(term, language='en', last=False): global wikiuri if not '%' in term: if isinstance(term, unicode): t = term.encode('utf-8') else: t = term
else: # cand[0] is subject if can_role: feature[i][0] = 1 else: feature[i][0] = 0 ############################################################ # Substitute and google it if pron_found and feature[i][0] == -1: latter_sent = [] for j in range(0, len(broken_tokens[i * 2 + 1]) - 1): latter_sent.append(str(broken_tokens[i * 2 + 1][j]['word'])) latter_sent[pronoun_index] = candidate_list[i][0] C0_BJ = search.google_search(list_to_string(latter_sent)) latter_sent[pronoun_index] = candidate_list[i][1] C1_BJ = search.google_search(list_to_string(latter_sent)) ## # C1_BJ = 1000 C2_BJ = 0 if C0_BJ > C1_BJ * (1 + 0.1): feature[i][0] = 0 print 'google ans: ', origin_candidate_list[i][ 0], ' vs ', key_list[i] continue elif C1_BJ > C0_BJ * (1 + 0.1): feature[i][0] = 1 print 'google ans: ', origin_candidate_list[i][ 1], ' vs ', key_list[i]
html = r_tag.sub('', html) html = r_whitespace.sub(' ', html) return unescape(html).strip() def search(term): try: import search except ImportError, e: print e return term if isinstance(term, unicode): term = term.encode('utf-8') else: term = term.decode('utf-8') term = term.replace('_', ' ') try: uri = search.google_search('site:en.wikipedia.org %s' % term) except IndexError: return term if uri: return uri[len('http://en.wikipedia.org/wiki/'):] else: return term def wikipedia(term, language='en', last=False): global wikiuri if not '%' in term: if isinstance(term, unicode): t = term.encode('utf-8') else: t = term q = urllib.quote(t) u = wikiuri % (language, q) bytes = web.get(u) else: bytes = web.get(wikiuri % (language, term))
index = index + 1 for i in range(0, num_options): option = '' while True: if content[index] != '': option = option + " " + content[index] index = index + 1 break index = index + 1 option_list.append(option.strip()) print option_list results = search.google_search(question, num=10) score = [] for i in range(0, num_options): count = 0 for result in results: count = count + result['title'].count(option_list[i]) count = count + result['snippet'].count(option_list[i]) score.append(count) print score # if negative: # print "NOT" #print option_list[score.index(max(score))]
def response(voice_data, q, n): try: import main if main.run == True or main.crun == True: import random #used for random import speaker # 1: greeting and convos if main.person_says(["hey","hi","hello"]): counters() greeting = ["hey, how can I help you " + main.person_obj.name, "hey, what's up? " + main.person_obj.name, "I'm listening " + main.person_obj.name, "how can I help you? " + main.person_obj.name, "hello " + main.person_obj.name] greet = greeting[random.randint(0,len(greeting)-1)] q.put(main.asis_obj.name + ": " + greet + "\n") speaker.speech_output(greet) elif main.person_says(["good morning","good evening","good afternoon","good noon", "goodnight"]): counters() import times times.greeter(q) elif main.person_says(["how are you","what's up"]): counters() treating = ["I am doing great, " + main.person_obj.name + ". How are you?", "I am fine, " + main.person_obj.name + ". What about you?", "I'm listening to you, " + main.person_obj.name + ". Do you need some help?"] treat = treating[random.randint(0,len(treating)-1)] q.put(main.asis_obj.name + ": " + treat + "\n") speaker.speech_output(treat) elif main.person_says(["you're nice", "fine", "i'm good", "thank you", "thanks", "thankyou", "alright"]): counters() replying = ["That's nice to hear.", "I am happy to hear that.", "I am glad to hear that."] reply = replying[random.randint(0,len(replying)-1)] q.put(main.asis_obj.name + ": " + reply + "\n") speaker.speech_output(reply) elif main.person_says(["joke","jokes", "make me laugh"]): counters() replying = ["Why don't scientists trust atoms? Because........ they make up everything! hehe", "Why doesn't the sun go to college? ..... Because it has a million degrees! buhahaha", "I have many jokes about unemployed people..... sadly none of them work. lol", "What do you call a singing laptop?...... Its A Dell!", "Some people think prison is one word......... but to robbers it's the whole sentence.", "Why couldn't the leopard play hide and seek?...............Because he was always spotted. lol", "I needed a password eight characters long..............So I picked Snow White and the Seven Dwarves. Buhahaha"] reply = replying[random.randint(0,len(replying)-1)] q.put(main.asis_obj.name + ": " + reply + "\n") speaker.speech_output(reply) # 2: naming each other and name changes elif main.person_says(["what is your name","what's your name","tell me your name"]): counters() import names names.chatbot_name(q) elif main.person_says(["what is my name","what's my name","tell me my name"]): counters() import names names.user_name(q) elif main.person_says(["change my name"]): counters() import names names.change_name(q) # 3: quitting program elif main.person_says(["exit", "quit", "goodbye", "bye", "bye bye"]): counters() q.put(main.asis_obj.name + ": " + "Bye! I will miss you! " + main.person_obj.name + "\n") speaker.speech_output("Bye! I will miss you! " + main.person_obj.name) import sys #used for exiting the program try: sys.exit(0) except SystemExit as e: sys.exit(e) # 4: ask time elif main.person_says(["what's the time", "what is the time", "what is current time", "tell me the time","what time"]): counters() import times times.time_speaker(q) elif main.person_says(["what's the date", "what is the date", "what is today's adte", "tell me the date","what date"]): counters() import times times.date_speaker(q) # 5: search google elif main.person_says(["search for", "search"]) and 'youtube' not in main.voice_data and 'weather' not in main.voice_data and 'price' not in main.voice_data: counters() import search search.google_search(q) # 6: search youtube elif main.person_says(["youtube"]): counters() import search search.youtube_search(q) #7 rock paper scisorrs elif main.person_says(["game"]) and n == 1: counters() import game game.game_rps(q) #8 screenshot elif main.person_says(["capture my screen","screenshot"]): counters() import pyautogui #used for screenshot myScreenshot = pyautogui.screenshot() myScreenshot.save('D:/screen.png') speaker.speech_output("The screen has been captured and placed in drive D as screen.png") #9 calculation elif main.person_says(["plus","minus","multiply","divide","power","+","-", "x", "*","/", "add", "subtract"]): counters() import calc calc.calculate(q) #10: search prices of items elif main.person_says(["price of", "price for", "price"]): counters() import search search.price_search(q) #11 weather elif main.person_says(["weather"]): counters() import search search.weather_search(q) #12 definitions elif main.person_says(["definition", "definitions", "what is"]): counters() import search search.definitions(q) #13 Go background elif main.person_says(["go to background", "goto background", "go background"]): counters() import background import speaker q.put(main.asis_obj.name + ": " + "I'm going background. Call my name if you need help." + "\n") speaker.speech_output("I'm going background. Call my name if you need help.") main.brun = True background.background_loop(q) #14 opening apps elif main.person_says(["app", "application"]): counters() import apps apps.open_app() #15 play songs elif main.person_says(["sing me a song", "play a song", "play song"]): counters() from playsound import playsound playsound('song/song.mp3') else: if main.error_count0 == main.error_count: main.empty_count += 1 #print("RE Non-Related = " + str(main.empty_count)) if main.empty_count > 3: counters() import speaker q.put(main.asis_obj.name + ": " + "I'm going background. Call my name if you need help." + "\n") speaker.speech_output("I'm going background. Call my name if you need help.") import background main.brun = True background.bg_play(q) main.error_count0 = main.error_count except: pass
html = r_tag.sub('', html) html = r_whitespace.sub(' ', html) return unescape(html).strip() def search(term): try: import search except ImportError, e: print e return term if isinstance(term, unicode): term = term.encode('utf-8') else: term = term.decode('utf-8') term = term.replace('_', ' ') try: uri = search.google_search('site:irowiki.org/classic/ %s' % term) except IndexError: return term if uri: return uri[len('http://irowiki.org/classic/'):] else: return term def irowiki(term, last=False): global irouri if not '%' in term: if isinstance(term, unicode): t = term.encode('utf-8') else: t = term q = urllib.quote(t) u = irouri % (q) bytes = web.get(u) else: bytes = web.get(irouri % term)
def search(term): try: import search except ImportError, e: print e return term if isinstance(term, unicode): term = term.encode("utf-8") else: term = term.decode("utf-8") term = term.replace("_", " ") try: uri = search.google_search("site:en.wikipedia.org %s" % term) except IndexError: return term if uri: return uri[len("http://en.wikipedia.org/wiki/") :] else: return term def wikipedia(term, language="en", last=False): global wikiuri if not "%" in term: if isinstance(term, unicode): t = term.encode("utf-8") else: t = term
html = r_tag.sub('', html) html = r_whitespace.sub(' ', html) return unescape(html).strip() def search(term): try: import search except ImportError, e: print e return term if isinstance(term, unicode): term = term.encode('utf-8') else: term = term.decode('utf-8') term = term.replace('_', ' ') try: uri = search.google_search('site:doc.ubuntu-fr.org %s' % term) except IndexError: return term if uri: return uri[len('http://doc.ubuntu-fr.org/'):] else: return term def ubuntu_fr(term, last=False): global ubuntu_uri if not '%' in term: if isinstance(term, unicode): t = term.encode('utf-8') else: t = term q = urllib.quote(t) u = ubuntu_uri % (q) bytes = web.get(u) else: bytes = web.get(ubuntu_uri % (term))
def analyze_screen(): active = gw.getActiveWindow() print( 'Please run ApowerMirror and mirror your phone, and make sure the main window is selected on your computer.' ) was_selected = False searched = [] while True: active = gw.getActiveWindow() if active is not None and (active.title == 'ApowerMirror Main'): if not was_selected: was_selected = True print( 'The correct window is active. Please do not click away.') img = pyautogui.screenshot() left = active.left top = active.top right = active.left + active.width bottom = active.top + active.height img = img.crop((left, top, right, bottom)) if round(img.width / img.height, 1) == round(16.0 / 9.0, 1): # the phone is horizontal with a 16:9 ration, so we need to crop it # this happens when a screen recoded video of a vertical screen is played left = round(img.width * 0.34) right = round(img.width - (img.width * 0.34)) img = img.crop((left, 0, right, img.height)) # crop to the size of the game window TODO are these the correct dimensions in an actual game? game_left = img.width * 0.0375 # game_top = img.height * 0.0375 game_top = img.height * 0.1786 game_right = img.width * 0.9595 game_bottom = img.height * 0.6851 img = img.crop( (round(game_left), round(game_top), round(game_right), round(game_bottom))) img.save('img/screenshot.png') q_and_a = read_question(img) if q_and_a is not None and q_and_a[0] not in searched: question = q_and_a[0] searched.append(question) answers = q_and_a[1] results = google_search(question) results = re.sub('[^a-zA-Z0-9]', '', results).lower() answer_counts = [] total = 0 for answer in answers: answer_clean = re.sub('[^a-zA-Z0-9]', '', answer).lower() count = results.count(answer_clean) total += count answer_counts.append((answer, count)) for answer_count in answer_counts: if total == 0: percent = 0 else: percent = round(answer_count[1] / total, 2) * 100 print(answer_count[0] + ': ' + str(percent) + '%') else: if was_selected: print( 'You have clicked away from the main window of ApowerMirror. Please reselect that window.' ) was_selected = False
def searchhive(term): try: import search except ImportError, e: print e return term if isinstance(term, unicode): term = term.encode('utf-8') else: term = term.decode('utf-8') term = term.replace('_', ' ') try: uri = search.google_search('site:wiki.hive76.org %s' % term) except IndexError: return term if uri: return uri[len('http://wiki.hive76.org'):] else: return term def wikipedia(term, language='en', last=False): global hivewikiuri if not '%' in term: if isinstance(term, unicode): t = term.encode('utf-8') else: t = term
def search(term): try: import search except ImportError, e: print e return term if isinstance(term, unicode): term = term.encode('utf-8') else: term = term.decode('utf-8') term = term.replace('_', ' ') try: uri = search.google_search('site:doc.ubuntu-fr.org %s' % term) except IndexError: return term if uri: return uri[len('http://doc.ubuntu-fr.org/'):] else: return term def ubuntu_fr(term, last=False): global ubuntu_uri if not '%' in term: if isinstance(term, unicode): t = term.encode('utf-8') else: t = term
def searchhive(term): try: import search except ImportError, e: print e return term if isinstance(term, unicode): term = term.encode("utf-8") else: term = term.decode("utf-8") term = term.replace("_", " ") try: uri = search.google_search("site:wiki.hive76.org %s" % term) except IndexError: return term if uri: return uri[len("http://wiki.hive76.org") :] else: return term def wikipedia(term, language="en", last=False): global hivewikiuri if not "%" in term: if isinstance(term, unicode): t = term.encode("utf-8") else: t = term