def command_wiki(word): '''Post the wikipedia definition for a word''' definition = "" try: definition = wikipedia.summary(word, sentences=2) if len(definition) > 220: definition = wikipedia.summary(word, sentences=1) if len(definition) > 200: send_message(CHAN, definition[:197] + "...") else: send_message(CHAN, definition) elif len(definition) < 30: definition = wikipedia.summary(word, sentences=3) if len(definition) > 200: send_message(CHAN, definition[:197] + "...") else: send_message(CHAN, definition) else: send_message(CHAN, definition) except wikipedia.exceptions.DisambiguationError as e: send_message(CHAN, "Disambiguation: 1. " + e.options[0] + " 2. " + e.options[1] + " ...") except wikipedia.exceptions.PageError as e: send_message(CHAN, "Page error. Please try another word.")
def make_wiki_search(sent): global anna_answered network=is_connected() if network==1: sent += " fixforsearch" search = 0 count = 0 words = sent.split() countin = len(sent.split()) for i in range(0, countin): if (words[i] == "search") or (words[i] == "search?"): search = 1 break count = count + 1 if (search == 1) and (words[count + 1] != "fixforsearch"): newword = words[count + 1] print ("\n") print(AI_speaking,wikipedia.summary(newword)) elif (search == 1): audio_output("OK, but what should I search?") newword = input_type() print ("\n") print(AI_speaking,wikipedia.summary(newword)) else: return; print("\n\n",) audio_output("Hope you got the answer") anna_answered=True return; elif network==0: audio_output("Sorry I can't search anything now :/ I am not connected.") anna_answered=True
def inf(d, s): wikipedia.summary("Wikipedia") wikipedia.set_lang("ru") types = ['museum', 'park', 'church', 'zoo', 'train_station', 'stadium'] def param(t): content = urlopen( 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?language=ru&location=' + str(d) + ',' + str( s) + '&rankby=distance&types=' + t + '&key=' + apikey).read() c = json.loads(content.decode("utf-8")) c = c.get('results') if len(c) != 0: c = c[0].get('name') # print(c) m = wikipedia.search(c, results=5, suggestion=False) # print(m[0]) if len(m) != 0: textsong = wikipedia.summary(m, sentences=5, chars=1) if textsong != '': return textsong #print(textsong) # if len(wikipedia.search(c)) != 0: # st = wikipedia.page(c) # if st.content # print(st.content) for type in types: #i in range(6): temp = param(type) if temp: return temp
def make_wiki_search(sent): global anna_answered sent += " fixforsearch" search = 0 count = 0 words = sent.split() countin = len(sent.split()) for i in range(0, countin): if (words[i] == "search") or (words[i] == "search?"): search = 1 break count = count + 1 if (search == 1) and (words[count + 1] != "fixforsearch"): newword = words[count + 1] print ("\n") print (wikipedia.summary(newword)) elif (search == 1): print("OK, but what should I search?") newword = input_type() print ("\n") print (wikipedia.summary(newword)) else: return; print("\n\n",AI_speaking,"Hope you got the answer") anna_answered=True return;
def info(topic): response = {} response["type"] = "wiki" try: page = wikipedia.page(topic) response['title'] = page.title response['url'] = page.url response['content'] = wikipedia.summary(page.title,sentences = 5) if len(response['content']) < 200: response['content'] = wikipedia.summary(page.title,sentences = 10) except Exception as error: ename = type(error).__name__ if ename == 'DisambiguationError': page = wikipedia.page(error.options[0]) response['title'] = page.title response['url'] = page.url response['content'] = wikipedia.summary(page.title,sentences = 2) if len(response['content']) < 200: response['content'] = wikipedia.summary(page.title,sentences = 10) elif ename == 'HTTPTimeoutError': response['type'] = "error" response['error'] = "I couldn't reach wikipedia" elif ename == 'PageError': response['type'] = "error" response['error'] = "I couldn't find anything on wikipedia" else: response['type'] = "error" response['error'] = "Unknown error occured while reaching wikipedia" return response
def add_word(word): print "[+] Current search:", word, " [", cont + 1, "/", MAX_CRAWL, "]" try: ## Fetch summary summary = wikipedia.summary(word) except wikipedia.exceptions.PageError as e: e.message if len(WORDS) == 0: print "[!]" except wikipedia.exceptions.DisambiguationError as e: ## Choose a suggestion that explicitly has the word in it. If none, choose first suggestion try: suggestion = next(sug for sug in e.options if word.lower() in sug.lower()) except StopIteration: suggestion = e.options[0] print "[!] Ambiguous term, using:", suggestion # print e.options summary = wikipedia.summary(suggestion) ## Append term and summary WORDS.append(word) SUMMARIES.append(summary) print " Summary fetched." print SUMMARIES[-1] print "\n"
def skwiki(titlequery): log.info("in skwiki") log.info(titlequery) try: return wikipedia.summary(titlequery, sentences=2). \ encode("ascii", "ignore") except wikipedia.exceptions.DisambiguationError as e: return wikipedia.summary(e.options[0], sentences=2). \ encode("ascii", "ignore")
def whoIs(query,sessionID="general"): try: return wikipedia.summary(query) except: for newquery in wikipedia.search(query): try: return wikipedia.summary(newquery) except: pass return "I don't know about "+query
def useCommandLineInput(): while True: print("\nwhat would you like to search?") toSearch = raw_input("enter here: ") if (toSearch == "q"): break try: print wikipedia.summary(toSearch, sentences = 2) except wikipedia.exceptions.DisambiguationError: print "there was an error!"
def send_wiki_info(who, text): answ=" ".join(text) if(answ[-1] == "?"): answ = answ[:-1] wikipedia.set_lang("ru") try: resp=wikipedia.summary(answ, sentences=6, chars=1, auto_suggest=False, redirect=True) except wikipedia.exceptions.DisambiguationError as error: resp=wikipedia.summary(error.options[0], sentences=6, chars=1, auto_suggest=False, redirect=True) except wikipedia.exceptions.WikipediaException: resp=wikipedia.summary(answ, sentences=6, chars=0, auto_suggest=True, redirect=True) bot.messages.send(peer_id=who, random_id=random.randint(0, 200000),message=resp)
def result(message): wikipedia.set_lang("en") #here we get message from user ij = message.text #here we say that ij is string string = ij #here i`ll say for python "Don`t read f*****g command /wiki, and read all latter from 6 to 99 " tj = string[6:99] #here is stupid debug. I`m not smart and i send result of wikipedia.summary to console print(wikipedia.summary(tj)) #here bot send to user result of this shity magic. bot.reply_to(message,wikipedia.summary(tj))
def get_random_articles_v2(): """Retrieves random articles until the user types 'stop' """ ans = input('Press enter to continue or stop to stop: ') while ans != 'stop': try: print(wikipedia.summary(wikipedia.random())) print() ans = input('Press enter to continue or stop to stop: ') except wikipedia.exceptions.DisambiguationError: print(wikipedia.summary(wikipedia.random())) print() ans = input('Press enter to continue or stop to stop: ')
def downloadArticle(self, article_title, data_path): output_file = os.path.join(data_path, '{:}.json'.format(article_title)) if os.path.isfile( output_file ): print(article_title + "exists, skipping") return try: wikipedia.set_lang('simple') summary = wikipedia.summary(article_title, sentences=1) wikipedia.set_lang('en') text = wikipedia.summary(article_title) except wikipedia.exceptions.PageError, e: return
def OnEnter(self, event): input = self.txt.GetValue() input = input.lower() try: #wolframalpha app_id = "YOUR APP ID" client = wolframalpha.Client(app_id) res = client.query(input) answer = next(res.results).text print answer except: #wikipedia print wikipedia.summary(input)
def getWiki(activity): pattern = re.compile("\\b(of|the|in|for|at|check|find|how|how\'s|is|tell|me|check|out|about|wiki|wikipedia|summarize)\\W", re.I) string = re.sub(pattern, "", activity) if "summarize" in activity or "summary" in activity: result = wikipedia.summary(string[len('summarize'):], sentences = 2) elif "wiki" in activity or "wikipedia" in activity: result = wikipedia.summary(activity[len('wiki'):]) else: try: result = wikipedia.search(string,results=10,suggestion=False) except Exception, e: result = wikipedia.search(string,results=10,suggestion=True)
def search(): os.system("say 'What do you think of that? '") searchs=raw_input("What do you think of that? ") searchs=searchs.lower() searchsWords = searchs.split() for searchsword in reversed(searchsWords): if searchsword in stop: searchsWords.remove(searchsword) os.system("say 'Did you know that '") os.system("say " + searchsWords[0]) os.system("say ' is;'") print("Did you know that " + searchsWords[0] + " is;") print wikipedia.summary(searchsWords[0]) search()
def Positive(): os.system("say 'That is good to hear!! But can you tell me why? '") searchGood=raw_input("That is good to hear!! But can you tell me why? ") searchGood=searchGood.lower() searchGoodWords = searchGood.split() for goodword in reversed(searchGoodWords): if goodword in stop: searchGoodWords.remove(goodword) os.system("say 'Did you know that '") os.system("say " + searchGoodWords[0]) os.system("say ' is;'") print("Did you know that " + searchGoodWords[0] + " is;") print wikipedia.summary(searchGoodWords[0]) search()
def Negative(): os.system("say 'Well, that sucks!!! Why is that? '") searchBad=raw_input("Well, that sucks!!! Why is that? ") searchBad=searchBad.lower() searchBadWords = searchBad.split() for badword in reversed(searchBadWords): if badword in stop: searchBadWords.remove(badword) os.system("say 'Did you know that '") os.system("say " + searchBadWords[0]) os.system("say ' is;'") print("Did you know that " + searchBadWords[0] + " is;") print wikipedia.summary(searchBadWords[0]) search()
def searchwiki(question): key = wikipedia.search(question) app.logger.info(repr("searching wikipedia for" + str(question))) if key: try: answer = wikipedia.summary(key[0],sentences=1) except Exception: m = wikipedia.page(wikipedia.search(key[0])) answer = wikipedia.summary(m.title,sentences=1) else: answer = False return answer
def orgsum(request): org = "cia" try: orginfo = wikipedia.summary(org) except wikipedia.exceptions.DisambiguationError as e: options = e.options return HttpResponse(options) orginfo = wikipedia.summary(org) return HttpResponse(orginfo)
def OnEnter(self, event): input = self.txt.GetValue() input = input.lower() try: #wolfram data app_id = "GA3WYQ-9EW3ERRJ4W" client = wolframalpha.Client(app_id) res = client.query(input) answer = next(res.results).text print answer except: #wikipedia input = input.split(' ') input = " ".join(input[2:]) print wikipedia.summary(input)
def Wiki_Function(self,query, detail=0,tr="en"): #if detail = 0, minimum details, if 1, complete wiki page self.fo=open("wiki.txt","w") reload(sys) # Reload does the trick! sys.setdefaultencoding('UTF8') wikipedia.set_lang("en") if tr == "hi": wikipedia.set_lang("hi") self.tag = wikipedia.page(query) if detail == 0: print(wikipedia.summary(query, sentences=2)) self.fo.write(wikipedia.summary(query, sentences=2)) elif detail == 1: self.fo.write(tag.content) print(self.tag.content) self.fo.close()
def wikipedia_fetch(title): """ returns a tuple containing the url to a page and a 3 sentence summary. """ try: pg = page(title) smry = summary(title, sentences=3) except WikipediaException, e: raise WikipediaException(e)
def question(): os.system('say "Ask your question"') r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) try: input = r.recognize_google(audio) os.system('say ' + input) except sr.UnknownValueError: print("unknown value error") except sr.RequestError: print("Cannot request that") #wikipedia.set_lang("en") try: #wolframalpha app_id = "your_appid" client = wolframalpha.Client(app_id) res = client.query(input) answer = next(res.results).text print answer os.system('say ' + answer) except: #wikipedia text = wikipedia.summary(input, sentences = 2) text = text.replace(u'\u2013', '') text = text.replace(u'\'', '') text = text.replace(u';', '') text = re.sub(r'\([^)]*\)', '', text) text = str(text) print text os.system('say ' + text) input = '' return 0
def disambiguate(word, e): try: ## Print all suggestions # for option in e.options: # print option # Choose a suggestion that explicitly has the word in it. # suggestion = next(sug for sug in e.options if word.lower() in sug.lower()) ## Choose suggestion at random suggestion = random.choice(e.options) except StopIteration: ## If none, choose first suggestion suggestion = e.options[0] try: # print "Trying to use " + suggestion ## Fetch new summary summary = wikipedia.summary(suggestion) print "[!] Ambiguous term, using:", suggestion # print e.options return summary except wikipedia.exceptions.DisambiguationError as err: # print err.options return disambiguate(suggestion, err) except wikipedia.exceptions.PageError as err: print err.message return disambiguate(suggestion, e)
def get_terms(key_words): terms= [] topTen= get_tuples(key_words) #topTen=key_words i=0 added=0 while added<10 and i<len(topTen): print added word=topTen[i][1] try: if(wiki_title_match(word)): print i #print wikipedia.summary(topTen[i][1]) terms.append((wikipedia.page(word).url,word," ".join(wikipedia.summary(word).split(' ')[:50])+"...")) added+=1 except (wikipedia.exceptions.DisambiguationError, wikipedia.exceptions.PageError,wikipedia.exceptions.WikipediaException): print "ERROR" print i print "no data" i+=1 return terms
def wiki_history(option, opt_str, value, parser): """ used to show history and query the word in it again. """ length = len(parser.rargs) if length > 1: parser.error(colored("option -h can't handle more than 1 arguments!", "red", attrs=["bold"])) elif length == 0: with open("history.txt", "r+") as history_file: for nums, lines in enumerate(history_file): print nums + 1, lines else: number = int(parser.rargs[0]) with open("history.txt", "r+") as history_file: lines = history_file.readlines() if len(lines) < number: parser.error(colored("number too big!!!", "red", attrs=["bold"])) try: text = summary(lines[number - 1]) w_print(text, "white", lines[number - 1], "green") except DisambiguationError as error: # the search term may refers to mutiple choices errors = [error.encode("utf-8") for error in error.options] message = '"{0}" may refer to: \n{1}'.format(error.title, "\n".join(errors)) parser.error(colored(message, "red", attrs=["bold"])) exit(1)
def wiki_func(paras, infos): """中文维基百科查询""" wikipedia.set_lang("zh") candidates = wikipedia.search(paras) if len(candidates) <= 0: return { 'text': 'not found', } else: summary = None for keyword in candidates: try: summary = wikipedia.summary(keyword, sentences=1) break except Exception: # 可能发生歧义异常,见 wikipedia 文档 continue if summary: answer = decode_to_unicode(summary) + \ u'\n候选关键词: %s' % u', '.join(candidates) return { 'text': answer, } else: return { 'text': 'not found', }
def wiki_request(name): ''' This method will return the 2 first sentences of the wikipedia page of the given name ''' try: name_wpp = wikipedia.page(name) name_wpp = name_wpp.title sentence = wikipedia.summary(name_wpp, sentences=2) except wikipedia.exceptions.DisambiguationError: name_wpp = wikipedia.page(name + ' cyclisme') name_wpp = name_wpp.title sentence = wikipedia.summary(name_wpp, sentences=2) except wikipedia.exceptions.PageError: sentence = "Pas de fiche WP" return sentence
def Menu(): print(w.summary('Dinosaurs', sentences = 4)) DinoInfo = 'l' while DinoInfo!='e': print(''' Hello Prehistoric Explorers! Millions of years ago, huge beings known as Dinosaurs used to roam this land. As time has passed and these animals have gone extinct, more and more information about these wondourous animals have been collected. YOU now have the chance to learn in depth about different Dinosaurs! Choose from the options below on what you would like to learn today: a. Learn about certain Dinosaurs and their characteristics! b. What kind of diet do certain Dinosaurs follow? c. What's going on with these Dinosaur names and where were these Dinos found? d. Lets learn about the period where these Dinos came from! e. I DONT LIKE DINOS! LET ME LEAVE TO GET COFFEE! To choose, type either a, b, c, d, or e. ''') DinoInfo = raw_input('What is your choice for today? ').lower() if DinoInfo == 'a': Char() elif DinoInfo == 'e': quit() else: print('RAWR! DO YOU NOT KNOW HOW TO READ OR DO YOU NEED GLASSES? CHOOSE A VALID CHOICE OR GET LOST!')
talk('Okay, here are your images! Have Fun!') else: Input = Input talk('Searching...') try: try: res = client.Input(Input) outputs = next(res.outputs).text talk('Alpha says') talk('Gotcha') talk(outputs) except: outputs = wikipedia.summary(Input, sentences=3) talk('Gotcha') talk('Wikipedia says') talk(outputs) except: talk("searching on google for " + Input) say = Input.replace(' ', '+') webbrowser.open('https://www.google.co.in/search?q=' + Input) talk('Next Command! Please!')
def TaskExecution(self): print("Initializing Jarvis...") wishMe() while True : self.query = self.takeCommand().lower() if 'wikipedia' in self.query : speak('Searching Wikipedia...') self.query = self.query.replace("wikipedia","") self.query = self.query.replace("according to wikipedia","") results = wikipedia.summary(self.query,sentences=2) print(results) speak("According to wikipedia") speak(results) elif "mute" in self.query : pyautogui.press("volumemute") elif "unmute" in self.query : pyautogui.press("volumemute") elif "pause" in self.query: pyautogui.press("playpause") elif "start" in self.query: pyautogui.press("playpause") elif 'old are you' in self.query : current_day = datetime.datetime.now() build_day = datetime.datetime(2021, 2, 8) diff = current_day - build_day speak('I am' + str(diff.days)+'days old') elif 'open youtube' in self.query : webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open("youtube.com") elif 'open chrome' in self.query : webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open("google.com") elif 'open google' in self.query : webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open("google.com") elif 'open wikipedia' in self.query : webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open("wikipedia.com") elif 'play ' in self.query: song = self.query.replace('play','') speak ('ok playing') pywhatkit.playonyt(song) elif 'time' in self.query: strTime = datetime.datetime.now().strftime("%I:%M %p") speak (f"Sir , the time is {strTime}") elif 'code' in self.query : codePath = "C:\\Users\\user\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe" os.startfile(codePath) elif 'send an email' in self.query : dict1 = {ids in which you have to send emails} try : speak("whom do you want to send") self.query = self.takeCommand().lower() for j in dict1.keys(): if self.query == j : person = dict1[j] speak("What should I say?") content = self.takeCommand() sendEmail(person,content) speak("Email has been sent!") except Exception as e : print (e) speak("Sorry sir but the e-mail was not sent ") elif 'joke' in self.query : joke = pyjokes.get_joke() print(joke) speak(joke) elif 'are you' in self.query: reply1 = 'I am very good and hope same for you' print(reply1) speak(reply1) elif 'were you made' in self.query : reply2 = "I was created by Mr. Abhinav on 8th of feb midnight" print(reply2) speak(reply2) elif "go die" in self.query : reply3 = "I'm sorry i can't do that ......I can't leave you like this" print(reply3) speak(reply3) elif "mar jao" in self.query : reply3 = "I'm sorry i can't do that ......I can't leave you like this" print(reply3) speak(reply3) elif "score" in self.query : reply4 = "Sure see this" speak(reply4) webbrowser.open("https://www.cricbuzz.com/cricket-match/live-scores") elif 'about yourself' in self.query: reply5 = "I am your personal assistant . and i can do anything for you like play music or send email or whatsapp anyone" print(reply5) speak(reply5) elif "creator" in self.query : reply6 = "Abhinav is my creator , he is soon going to be an aerospace engineer , he lives in lucknow. Abhinav loves coding." print(reply6) speak(reply6) elif 'who is' in self.query : person = self.query.replace('who is ','') info = wikipedia.summary(person,2) print(info) speak(info) elif 'what is' in self.query : person = self.query.replace('what is ','') info = wikipedia.summary(person,2) print(info) speak(info) elif 'tell me about' in self.query : person2 = self.query.replace('tell me about', '') info = wikipedia.summary(person2,10) print(info) speak(info) elif 'game' in self.query : speak('OK starting the guess game') speak('Guess a number between 1 to 10') a = None b = random.randint(1,10) guess = 0 while (a!=b): r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 audio = r.listen(source) try : print("Recognizing...") a = r.recognize_google(audio) print(f"user said: {a}\n") a = int(a) except Exception as e : # print (e) print ("Say that again please...") if (a < b) : speak('lesser, try again') guess = guess + 1 elif (a > b) : speak('greater, try again') guess = guess + 1 elif (a == b) : speak('Gotcha !! you got it in') speak(str(guess)) speak('times') elif 'bye bye' in self.query: speak("Initiating shutting command.....Good-bye sir") exit() elif "camera" in self.query or "take a photo" in self.query: ec.capture(0, "jarvis camera","img.jpg") elif 'date' in self.query: today = date.today() print(today) speak(today) elif 'day' in self.query : today = date.today() d1 = today.strftime("%d/%m/%Y") day, month, year = (int(x) for x in d1.split('/')) ans = datetime.date(year, month, day) print (ans.strftime("%A")) speak(ans.strftime("%A")) elif 'news' in self.query: url = ('https://newsapi.org/v2/top-headlines?country=in&apiKey=3103661539ec4deca15cd122cd5381ad') response = requests.get(url) text = response.text my_json = json.loads(text) for i in range(0, 5): print((i+1),'.',my_json['articles'][i]['title']) speak(my_json['articles'][i]['title']) elif 'instagram' in self.query : webbrowser.get('C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s').open("instagram.com") elif 'pagal' in self.query : speak ('who speaks is the one who is') elif 'temperature' in self.query : speak("Which city sir") r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") audio = r.listen(source) try: print("Recognizing...") place = r.recognize_google(audio , language= 'en-in') print(f"user said: {place}\n") except Exception as e: print('Say that again please') place = none search = f"Weather in {place}" url = f"https://www.google.com/search?q={search}" r = requests.get(url) soup = BeautifulSoup(r.text , "html.parser") update = soup.find("div" , class_="BNeawe").text print(f"{search} now is {update}") speak(f"{search} now is {update}") elif 'mails' in self.query : webbrowser.open('https://mail.google.com/') elif 'note' in self.query: speak("What would you like me to write down?") r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") audio = r.listen(source) try: print("Recognizing...") self.query = r.recognize_google(audio , language= 'en-in') print(f"user said: {self.query}\n") except Exception as e: print('Say that again please') self.query = none note(self.query) print("I've made a note of that") elif 'remember' in self.query: speak("What would you like me to remember?") r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") audio = r.listen(source) try: print("Recognizing...") self.query = r.recognize_google(audio , language= 'en-in') print(f"user said: {self.query}\n") except Exception as e: print('Say that again please') self.query = none note(self.query) print("I've stored your messege") elif 'blackboard' in self.query: reply5 = "Opening blackboard" speak(reply5) webbrowser.open("https://learn.upes.ac.in//webapps//portal//execute//tabs//tabAction?tab_tab_group_id=_141_1") elif 'sing a song' in self.query: speak("although i am having a sour throat stil i can try ") playsound('C:\\Users\\user\\OneDrive\\Documents\\jarvis song.mp3') elif 'thank you' in self.query : speak("Pleasure sir , it's my duty to make you happy") elif 'open whatsapp' in self.query : speak("opening") codePath = "C:\\Users\\user\\AppData\\Local\\WhatsApp\\WhatsApp.exe" os.startfile(codePath) elif 'send message' in self.query : d = dict(name1=phone number,name2=phone number2) try : speak("whom do you want to send") receiver_name = self.takeCommand().lower() receiver_name= receiver_name.lower() for j in d.keys(): if receiver_name == j : receiver_number = str(d.get(receiver_name)) receiver_number = "+91" + receiver_number print(receiver_number) speak("What should I say?") content = self.takeCommand() speak("What time you want to send the messege") msg_time = str(self.takeCommand().lower()) msg_time = msg_time.replace(' ','') hour = int(msg_time[:2]) minute = int(msg_time[2:]) content[0].upper() kit.sendwhatmsg(receiver_number,content,hour,minute) speak("Message has been sent") except Exception as e : print (e) speak("Sorry sir but the messege was not sent ") elif 'jarvis' in self.query: client = wolframalpha.Client('6RLLXQ-UK69UXVU2T') try: print("Yes sir what can i do for you") speak("Yes sir what can i do for you") question = self.takeCommand() query = str(question) res = client.query(query) print(next(res.results).text) speak(f"The answer is {next(res.results).text}") except: print("I dont know that but i am improving") speak("Sorry , i dont know that but i am improving") elif 'alarm' in self.query : nn == int(datetime.datetime.now().hour) if nn == 1: music_dir = "C:\\Users\\user\\Documents\\my_assitant.py\\alarm_beeps.mp3" songs = os.listendr(music_dir) os.startfile(os.path.join(music_dir,songs[0])) elif "shutdown the system" in self.query : pyautogui.confirm('Shall I proceed?') speak('ok shutting down') os.system("shutdown /s /t 5") elif "new tab" in self.query: pyautogui.hotkey("ctrl","t") elif "restart the system" in self.query : os.system("shutdown /r /t 5") elif "go to sleep" in self.query : os.system("rundll123.exe powrprof.dll,SetSuspendState 0,1,0") elif 'switch the window' in self.query : speak("Switching...") pyautogui.keyDown("alt") pyautogui.press("tab") pyautogui.press("alt") elif 'start menu' in self.query : pyautogui.click(0,1079) elif 'blinking mouse' in self.query : j=0 while j < 100 : pyautogui.click(500,540) pyautogui.click(1500,540) j = j + 1 elif "screenshot" in self.query : pyautogui.keyDown("start") pyautogui.keyDown("prtsc")
request = ai.text_request() request.query = query response = request.getresponse() json_data = (response.read()) say = json.loads(json_data) # print(say) speech = say['result']['fulfillment']['speech'] search = speech.split(":") if search[0] == "Google" or search[0] == "Google and Google": G_Search(search[1]) # wb.open_new_tab(google_search+search[1]) print() elif search[0] == "Wiki": try: wiki_say = wiki.summary(search[1]) print(color(BOLD + wiki_say + END + "\n", "green")) except wiki.exceptions.DisambiguationError: print( color( BOLD + "Try to google it because it is very confusing for me" + END, "red")) elif search[0] == "Youtube": Y_Search(search[1]) # wb.open_new_tab(youtube_search+search[1]) print("") elif search[0] == "Drive": wb.open_new_tab(google_drive) print("")
def info(topic, lines=3): '''Gives information on a topic from wikipedia.''' spe = wikipedia.summary(topic, sentences=lines) print(spe)
import wikipedia result = wikipedia.summary("python", sentences=2) print(result)
def Program(): engine = pyttsx3.init('sapi5') engine.setProperty('volume', 1.0) engine.setProperty('rate', 200) client = wolframalpha.Client('P32Q9J-976AAG95X6') voices = engine.getProperty('voices') engine.setProperty('voice', voices[len(voices) - 1].id) def speak(audio): print('Anna: ' + audio) engine.say(audio) engine.runAndWait() def greetMe(): currentH = int(datetime.datetime.now().hour) if currentH >= 0 and currentH < 12: speak('Good Morning!') if currentH >= 12 and currentH < 16: speak('Good Afternoon!') if currentH >= 16 and currentH != 0: speak('Good Evening!') def myCommand(): r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 r.adjust_for_ambient_noise(source, duration=1) r.energy_threshold = 300 audio = r.listen(source) try: query = r.recognize_google(audio, language='en-in') print('User: '******'\n') except sr.UnknownValueError: print("!") query = myCommand() return query def Command(): r = sr.Recognizer() with sr.Microphone() as source: r.pause_threshold = 1 r.adjust_for_ambient_noise(source, duration=1) r.energy_threshold = 300 audio = r.listen(source) try: query = r.recognize_google(audio, language='en-in') except sr.UnknownValueError: query = Command() return query def online(): speak('hello sir') speak('starting all system applications') speak('installing all drivers') speak('every driver is installed') speak('all systems have been started') speak('now i am online sir') def shutdown(): speak('understood sir') speak('connecting to command prompt') speak('shutting down your computer') os.system('shutdown -s') def gooffline(): speak('ok sir') speak('closing all systems') speak('disconnecting to servers') speak('going offline') quit() greetMe() online() speak('How may I help you?') while True: query = myCommand() query = query.lower() if 'open youtube' in query or 'youtube' in query: speak('okay') webbrowser.open('www.youtube.com') elif 'open google' in query or 'google' in query: speak('okay') webbrowser.open('www.google.co.in') elif 'open gmail' in query or 'gmail' in query: speak('okay') webbrowser.open('www.gmail.com') elif "what\'s up" in query or 'how are you' in query: stMsgs = [ 'Just doing my thing!', 'I am fine!', 'Nice!', 'I am nice and full of energy' ] speak(random.choice(stMsgs)) elif 'send mail' in query or 'send email' in query or 'email' in query: speak('Who is the recipient? ') recipient = myCommand() if 'me' in recipient: speak('What should I say? ') content = myCommand() receiver_email = '*****@*****.**' else: speak('Receiver Email Address please!') receiver_email = myCommand() speak('What should I say? ') content = myCommand() try: server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login("*****@*****.**", 'Sangam123@') server.sendmail('*****@*****.**', receiver_email, content) server.close() speak('Email sent!') except: speak( 'Sorry Sir! I am unable to send your message at this moment!' ) elif 'bye' in query or 'nothing' in query or 'abort' in query or 'stop' in query: gooffline() elif 'hello' in query: speak('Hello Sir') elif 'shutdown' in query: shutdown() elif 'play music' in query or 'next music' in query or 'music' in query: music_folder = "D:\\song\\1920_Evil_Returns_(2012)_IndiaMp3.Com\\1920 - Evil Returns (2012)\\songs\\" music = ["Apnaa", "Jaavedaan Hai", "Khud", "Majboor", "Uska"] random_music = music_folder + random.choice(music) + '.mp3' player = vlc.MediaPlayer(random_music) player.play() speak('Okay, here is your music! Enjoy!') while (Command() not in ["stop", "stop music"]): pass else: player.stop() else: query = query speak('Searching...') try: try: res = client.query(query) results = next(res.results).text speak('WOLFRAM-ALPHA says - ') speak('Got it.') speak(results) except: results = wikipedia.summary(query, sentences=2) speak('Got it.') speak('WIKIPEDIA says - ') speak(results) except: webbrowser.open('www.google.com') nextmsgs = [ 'Next Command! Sir!', 'What more I can do for you sir!', 'Anything else! Sir!', 'What else can i do', 'Any more request sir...' ] speak(random.choice(nextmsgs))
def getSummary(query): summary = wikipedia.summary(query) return summary
def run(): def ask(): talk('how will you give comand text or voice') n = input('how will you give comand text/voice') if n == "voice": comm = take() elif n == 'text': comm = inputt() else: ask() return comm war() com = ask() if 'play' in com: song = com.replace('play', '') print('playing' + song) pywhatkit.playonyt(song) run() elif 'time' in com: time = datetime.datetime.now().strftime('%I:%M %p') print(time) talk(time) tim.sleep(5) run() elif 'date' in com: d2 = today.strftime("%d %B, %Y") print("d2 =", d2) talk(d2) tim.sleep(5) run() elif 'joke' in com: talk(pyjokes.get_joke()) run() tim.sleep(5) elif 'create text file' in com: fn = file_name() n = fn + ".txt" data = dat() fh = open(n, 'w') fh.write(data) fh.close() tim.sleep(5) run() elif 'create word document' in com: fn = file_name() nf = fn + ".rtf" fh = open(nf, 'w') data = dat() fh.write(data) fh.close() tim.sleep(5) run() elif 'about ' in com: about = com info = wikipedia.summary(about, 1) print(info) talk(info) run() elif 'open pycharm' in com: path = 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\JetBrains\PyCharm Community Edition 2020.3.lnk' os.startfile(path) talk('opening pycharm') tim.sleep(5) elif ' open vlc' in com: path = 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\VideoLAN\VLC media player.lnk' os.startfile(path) talk('VLC') tim.sleep(5) elif 'open notepad' in com: path = 'C:\\Users\sirisha\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\\Notepad.lnk' os.startfile(path) elif (' go to bharat ane nenu' or 'go to bharatanenenu') in com: path = "D:\Bharat Ane Nenu (2018) Telugu v2 True HQ HDRip - 720p - x264 - AAC - 1.4GB.mkv" os.startfile(path) talk("playing bharat ane nenu") run() elif ' k' in com: path = "D:\\" os.startfile(path) run() elif 'open' in com: op = com.replace("open ", 'www.') cp = op.replace('www.', '') talk("opening" + cp) c = ".com" url = op + c print(url) ch = 'C:/ProgramData/Microsoft/Windows/Start Menu/Programs/Google Chrome.lnk %s' webbrowser.open(url) run() elif 'search' in com: opp = se() op = '/search?q=' ad = opp.replace(' ', '+') print(ad) cp = "www.google.com" talk("searching" + opp) url = cp + op + ad print(url) ch = 'C:/ProgramData/Microsoft/Windows/Start Menu/Programs/Google Chrome.lnk %s' webbrowser.open(url) tim.sleep(5) run() elif 'stop' in com: print('stop') war() tim.sleep(20) elif ('shut down' or 'shutdown' or 'power off') in com: shut_down() else: talk('say that again') run()
def play(): btn2['state'] = 'disabled' btn0['state'] = 'disabled' btn1.configure(bg='orange') wishme() while True: btn1.configure(bg='orange') query = takeCommand().lower() if 'exit' in query: #TO EXIT THE ASSISTANT btn1.configure(bg='#5C85FB') btn2['state'] = 'normal' btn0['state'] = 'normal' window.update() speak( "Closing myself vijit, Please remeber me again! Have a good day" ) var.set("Closing Lydia...") window.update() var1.set("User Said:") window.update() var.set("Welcome") window.update() break #FOR OPENING WEB BROWSER PREOGRAMS elif 'wikipedia' in query: #FOR WIKIEPEDIA if 'open wikipedia' in query: #FOR SEARCHING WIKIPEDIA ON INTERNET webbrowser.open('wikipedia.com') else: try: speak("searching wikipedia" ) #FOR SEARCHING WIKIPEDIA FROM ASSISTANT query = query.replace("according to wikipedia", "") results = wikipedia.summary(query, sentences=2) var1.set("User Said:") window.update() speak("According to wikipedia") var1.set("User Said:") window.update() var.set(results) window.update() speak(results) except Exception as e: var.set('sorry sir could not find any results') window.update() speak('sorry sir could not find any results') elif 'open youtube' in query: #FOR YOUTUBE var1.set("User Said:") window.update() var.set('opening Youtube') window.update() speak('opening Youtube') webbrowser.open("www.youtube.com") elif 'open google' in query: #FOR GOOGLE var1.set("User Said:") window.update() var.set('opening google') window.update() speak('opening google') webbrowser.open("www.google.com") elif 'open gmail' in query: #FOR GMAIl var1.set("User Said:") window.update() var.set("opening gmail") window.update() speak("opening gmail") webbrowser.open('www.gmail.com') elif 'whatsapp' in query: #FOR WHATASPP(WEB) var1.set("User Said:") window.update() var.set("opening whatsapp") window.update() speak("opening whatsapp") webbrowser.open("https://web.whatsapp.com/") elif 'send email' in query: #SENDING EMAIL speak("opening gmail to send email") webbrowser.open( "https://mail.google.com/mail/u/0/#inbox?compose=new") #------------------------------------------------------------------------------- #OPENING PROGRAMS/FILES IN COMPUTER elif 'open zoom' in query: #OPENING ZOOM var1.set("User Said:") window.update() var.set("opening zoom") speak("opening zoom") os.startfile( "C:\\Users\\vijit\\AppData\\Roaming\\Zoom\\bin\\Zoom.exe") elif 'open atom' in query: #OPENING ATOM IDE var1.set("User Said:") window.update() var.set("opening atom") window.update() speak("opening atom") os.startfile("C:\\Users\\vijit\\AppData\\Local\\atom\\atom.exe") elif 'current time' in query: #CURRENT TIME strTime = datetime.datetime.now().strftime("%H:%M:%S") var1.set("User Said:") window.update() var.set(f"The time is {strTime}") speak(f"The time is {strTime}") window.update() elif 'open sublime text' in query: #OPENING SUBLIME TEXT var1.set("User Said:") window.update() var.set("opening text") window.update() speak("opening sublime text") sub = "C:\Program Files\Sublime Text 3\sublime_text.exe" os.startfile(sub) elif 'open cmd' in query: #OPENING COMMAND PROMPT var1.set("user said") window.update() var.set("opening cmd") window.update() speak("opening command prompt") os.startfile("cmd.exe") elif 'open git bash' in query: #OPENING GIT BASH var1.set("User Said:") window.update() var.set("opening git bash") window.update() speak("opening git bash") bash = "C:\Program Files\Git\git-bash.exe" os.startfile(bash) elif 'open notepad' in query: #OPENING NOTEPAD var1.set("User Said:") window.update() var.set("opening notepad") window.update() speak("opening notepad") os.startfile("C:\\WINDOWS\\system32\\notepad.exe") elif 'open python' in query: #OPENING PYTHON var1.set("User Said:") window.update() var.set("opening python") window.update() speak("opening python") os.startfile("C:\\Users\\vijit\\anaconda3\\python.exe") elif 'recorder' in query: #NW var1.set("User Said:") window.update() var.set("opening obs recorder") window.update() speak("opening obs recorder") os.startfile( "C:\\Program Files\\obs-studio\\bin\\64bit\\obs64.exe") elif 'attendance' in query: #ATTENDANCE var1.set("User Said:") window.update() var.set("opening semester 5 attendance") window.update() speak("opening semester 5 attendance") os.startfile("C://Users//vijit//Desktop//ATTENDANCE 5 SEM.txt") elif 'alexa' in query: # var1.set("User Said:") window.update() var.set("opening Video") window.update() speak("opening video") os.startfile("C:\\Users\\vijit\\Videos\\2020-08-19 23-41-51.mkv") elif 'semester 5' in query: #SEMESTER 5 (VIDEOS) var1.set("User Said:") window.update() var.set("opening semester 5 study") window.update() speak("opening semester 5 study") os.startfile("C:\\Users\\vijit\\Videos\\SEMESTER 5") elif 'movies' in query: #OPENING LIST OF MOVIES var1.set("User Said:") window.update() var.set("opening list of movies") window.update() speak("opening list of movies") os.startfile("C:\\Users\\Nikita\\Desktop\\MINE\\movies.txt") elif 'dates' in query: #OPENING LIST OF MOVIES var1.set("User Said:") window.update() var.set("opening dates") window.update() speak("opening dates") os.startfile("C:\\Users\\Nikita\\Desktop\\MINE\\DATES.txt") elif 'example' in query: ved_dir = "C:\\VIJIT RAWAL\\VEDIOS" songs = os.listdir(ved_dir) var.set(songs) window.update() from random import randint r = randint(0, 4) print("\n") print(r) print("\n") os.startfile(os.path.join(ved_dir, songs[r])) elif 'pc' in query: speak("opening wps") os.startfile("This PC") #------------------------------------------------------------------------------- #CLOSING ALL APPLICATION elif 'shutdown' in query: #SHUTTING DOWN THE COMPUTER speak("shutting down ur computer") speak("closing all applications") os.system("taskkill/im atom.exe") os.system("taskkill/im notepad.exe") os.system("taskkill/im git-bash.exe") os.system("shutdown /s") elif 'close notepad' in query: #CLOSING NOTEPAD var1.set("User Said:") window.update() var.set("closing notepad") window.update() speak("closing notepad") os.system("taskkill/im notepad.exe") elif 'close cmd' in query: #CLOSING COMMAND PROMPT var1.set("User Said:") window.update() var.set("closing command prompt") window.update() speak("closing command prompt") os.system("taskkill/im cmd.exe") elif 'close atom' in query: #CLOSING ATOM IDE var1.set("User Said:") window.update() var.set("closing atom") window.update() speak("closing atom") os.system("taskkill/im atom.exe")
def main(): os.system('cls') # This Function will clean any # command before execution of this python file popup_var = popup_choice(f'{assname}', 'Do you want to run startup Sir ?') # This means you select yes if popup_var == 6: startup() fetch_pages() wishme() usrname() speak('Main function works fine and basic function were built Sir !') currenttime() log.write('Main function works fine and basic function were built Sir !' + '\n') while True: query = takecommand().lower() # All the commands said by user will be # stored here in 'query' and will be # converted to lower case for easily # recognition of command if 'wikipedia' in query: speak('Searching Wikipedia...') query = query.replace("wikipedia", "") results = wikipedia.summary(query, sentences=3) speak("According to Wikipedia") print(results) speak(results) currenttime() log.write('According to Wikipedia' + '\n') currenttime() log.write(results + '\n') elif 'youtube' in query: speak('Here you go to Youtube') webbrowser.open('https://www.youtube.com') currenttime() log.write('Here you go to Youtube' + '\n') elif 'google' in query: speak('Here you go to Google') webbrowser.open('https://www.google.com') currenttime() log.write('Here you go to Google' + '\n') elif 'stackoverflow' in query: speak('Here you go to Stack Over flow, Happy coding') webbrowser.open('https://www.stackoverflow.com') currenttime() log.write('Here you go to Stack Over flow, Happy coding' + '\n') elif 'time' in query: now = datetime.datetime.now() strtime = now.strftime('%H:%M:%S') speak(f'Sir !, the time is {strtime}') currenttime() log.write(f'Sir !, the time is {strtime}' + '\n') elif 'send an email' in query: try: speak("What should I say?") content = takecommand() speak("whome should i send") to = takecommand().lower() sendemail(to, content) speak("Email has been sent !") currenttime() log.write('Email has been sent !' + '\n') except Exception as e: print(e) speak("I am not able to send this email") currenttime() log.write(str(e) + '\n') currenttime() log.write('I am not able to send this email' + '\n') elif 'how are you' in query: jarvis_responses_list = [ "I'm great", "I'm fine", "I'm doing good", "Not Bad" ] jarvis_responses_result = random.choice(jarvis_responses_list) speak(jarvis_responses_result) currenttime() log.write(jarvis_responses_result + '\n') jarvis_questions_list = [ "How was your day Sir ?", "How about you Sir ?", "How are you Sir ?" ] jarvis_questions_result = random.choice(jarvis_questions_list) speak(jarvis_questions_result) currenttime() log.write(jarvis_questions_result + '\n') elif "what's your name" in query or "What is your name" in query: speak("My friends call me") speak(f'{assname}') currenttime() log.write(f"My friends call me {assname}" + '\n') elif 'exit' in query: speak("Thanks for giving me your time") currenttime() log.write('Thanks for giving me your time' + '\n') exit() elif "who made you" in query or "who created you" in query: speak("I have been created by Alireza Safari") currenttime() log.write('I have been created by Alireza Safari.' + '\n') elif 'flip a coin' in query: res = random.randint(1, 2) if res == 1: speak('Heads') currenttime() log.write('Heads' + '\n') elif res == 2: speak('Tails') currenttime() log.write('Tails' + '\n') else: popup_basic(f'{assname}', 'An Error Occurred') currenttime() log.write('An Error Occurred while flipping a coin' + '\n') elif "calculate" in query: app_id = "Wolframalpha api id" client = wolframalpha.Client(app_id) indx = query.lower().split().index('calculate') query = query.split()[indx + 1:] res = client.query(' '.join(query)) answer = next(res.results).text print("The answer is " + answer) speak("The answer is " + answer) currenttime() log.write('The answer is' + answer + '\n') elif "who am i" in query: speak("If you talk then definitely your human") currenttime() log.write('If you talk then definitely your human' + '\n') elif "why you came to world" in query: speak("Thanks to Alireza Safari. further It's a secret") currenttime() log.write("Thanks to Alireza Safari. further It's a secret" + '\n') elif 'what is love' in query: speak("It is 7th sense that destroy all other senses") currenttime() log.write("It is 7th sense that destroy all other senses" + '\n') elif "who are you" in query: speak("I am your virtual assistant created by Alireza Safari") currenttime() log.write('I am your virtual assistant created by Alireza Safari' + '\n') elif 'reason for you' in query: speak("I was created as a Fun project by Mister Alireza Safari") currenttime() log.write( 'I was created as a Fun project by Mister Alireza Safari' + '\n') elif 'lock window' in query: speak("locking the device") currenttime() log.write('Locking the device' + '\n') ctypes.windll.user32.LockWorkStation() elif 'shutdown system' in query: speak("Hold On a Sec ! Your system is on its way to shut down") currenttime() log.write( "Hold On a Sec ! Your system is on its way to shut down" + '\n') subprocess.call('shutdown / p /f') elif "don't listen" in query or "stop listening" in query: speak( f"for how much time you want to stop {assname} from listening commands" ) a = int(takecommand()) currenttime() log.write(f'{assname} is gonna be locked for {a} minute(s)' + '\n') time.sleep(a) print(a) elif "where is" in query: query = query.replace("where is", "") location = query speak("User asked to locate") speak(location) currenttime() log.write('User asked to locate' + location + '\n') webbrowser.open("https://www.google.nl / maps / place/" + location + "") elif "restart" in query: speak('Restarting the system in a sec Sir !') currenttime() log.write('Restarting the system in a sec Sir !' + '\n') subprocess.call(["shutdown", "/r"]) elif "hibernate" in query or "sleep" in query: speak('Hibernating the system in a sec Sir !') currenttime() log.write('Hibernating the system in a sec Sir !' + '\n') subprocess.call("shutdown / h") elif "log off" in query or "sign out" in query: speak('Logging off the system in a sec Sir !') currenttime() log.write('Logging off the system in a sec Sir !' + '\n') subprocess.call(["shutdown", "/l"]) elif "write a note" in query: speak("What should i write Sir ?") currenttime() log.write('What should i write Sir ?' + '\n') note = takecommand() file = open(f'{assname}.txt', 'w') speak("Sir, Should i include date and time") snfm = takecommand() if 'yes' in snfm or 'sure' in snfm: strtime = datetime.datetime.now().strftime("% H:% M:% S") file.write(strtime) file.write(" :- ") file.write(note) else: file.write(note) currenttime() log.write('Note file created successfully' + '\n') elif "show note" in query: speak("Showing Notes Sir !") currenttime() log.write('Showing notes Sir !' + '\n') file = open(f"{assname}.txt", "r") print(file.readlines()) speak(file.readline()) elif "jarvis" or f'{assname}' in query: wishme() speak(f"{assname} {version} in your service Mister") elif "weather" in query: # Google Open weather website # to get API of Open weather api_key = "Api key" base_url = "http://api.openweathermap.org / data / 2.5 / weather?" speak(" City name ") print("City name : ") city_name = takecommand() complete_url = base_url + "appid =" + api_key + "&q =" + city_name response = requests.get(complete_url) x = response.json() if x["cod"] != "404": y = x["main"] current_temperature = y["temp"] current_pressure = y["pressure"] current_humidity = y["humidity"] z = x["weather"] weather_description = z[0]["description"] print(" Temperature (in kelvin unit) = " + str(current_temperature) + "\n atmospheric pressure (in hPa unit) =" + str(current_pressure) + "\n humidity (in percentage) = " + str(current_humidity) + "\n description = " + str(weather_description)) currenttime() log.write(" Temperature (in kelvin unit) = " + str(current_temperature) + "\n atmospheric pressure (in hPa unit) =" + str(current_pressure) + "\n humidity (in percentage) = " + str(current_humidity) + "\n description = " + str(weather_description) + '\n') else: speak(" City Not Found ") currenttime() log.write('City Not Found' + '\n') elif "Good Morning" in query: speak('Have a nice day Sir !') currenttime() log.write('Have a nice day Sir !' + '\n') # most asked question from google Assistant elif "will you be my gf" in query or "will you be my bf" in query: speak("I'm not sure about, may be you should give me some time") currenttime() log.write( "I'm not sure about, may be you should give me some time" + '\n') elif 'search' in query: speak('What should i search for Sir !') ask_search = takecommand() try: webbrowser.open(ask_search) currenttime() log.write('Searched the results successfully Sir !' + '\n') except: speak("Sorry Sir !, Couldn't search what you asked for") currenttime() log.write("Sorry Sir !, Couldn't search what you asked for" + '\n') # Gives $ price to Rials elif 'dollar price' in query: json_data = requests.get( 'http://api.navasan.tech/latest/?api_key=Q7qZLgqv1jmtBDu0dgF6lw9TMpc1QfRN' ).json() json_usd = json_data['mex_usd_sell'] value = json_usd['value'] speak(f'Good Morning Sir ! $ price of today is {value} Tomans') currenttime() log.write( f'Good Morning Sir ! $ price of today is {value} Tomans' + '\n') elif not query or query == '': speak("Hmmm, You didn't say anything Sir !") currenttime() log.write("Hmmm, You didn't say anything Sir !" + '\n') else: speak( "Sorry Sir !, Your Command is not in my database wait for further updates, Thanks" ) currenttime() log.write( "Sorry Sir !, Your Command is not in my database wait for further updates, Thanks" )
work_list[search_query] = str(answer) except: speak( 'Sir i cant find any resource able to answer your question please elaborate your question ' ) q = q + 1 print( 'Sir i cant find any resource able to answer your question please elaborate your question ' ) elif 'brief' in arg or 'explain' in arg or 'search' and 'wikipedia' in arg: try: speak('what shall i search on wikipedia ') q = q + 1 print('what shall i search on wikipedia ') user_query = input('') result = wikipedia.summary(user_query) speak(result) q = q + 1 work_list[user_query] = str(result) except: print( 'I am unable to understand the wikipedia page you are referring to please elaborate' ) elif 'wake' in arg and 'me' in arg and 'up' in arg or 'alarm' in arg and 'set' in arg or 'alarm' in arg: speak( 'At what time will you like to wake up.\nPlease tell the time only' ) q = q + 1 print( 'At what time will you like to be alarmed.\nPlease tell the time only' )
if __name__ == "__main__": chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s' myvideo = YouTube("https://www.youtube.com/watch?v=5MgBikgcWnY") print(sr.__version__) wishMe() if True: query = takeCommand().lower() #query='open google' #logic for executing task based on query if 'wikipedia' in query: speak('searching wikipedia..') query = query.replace('wikipedia', '') results = wikipedia.summary(query, sentences=2) speak("according to wikipedia") print(results) speak(results) elif 'open youtube' in query: url = "youtube.com" webbrowser.get(chrome_path).open(url) elif 'open google' in query: url = "google.com" webbrowser.get(chrome_path).open(url) elif 'open stackoverflow' in query: webbrowser.open("stackoverflow.com")
import wikipedia while True: input = raw_input("Question: ") wikipedia.set_lang("hi") print wikipedia.summary(input)
import wikipedia import json stuff = open("presidents.json") presidents = json.load(stuff) for index, data in enumerate(presidents): print index presidents[index]["summary"] = wikipedia.summary(data["president"], sentences=5) presidents[index]["img"] = wikipedia.page(data["president"]).images[0] with open('complete-presidents.json', 'w') as f: f.write(json.dumps(presidents))
def main(): os.system('cls') f = open("C:\\Users\\Rajan Kumar Sah\\Desktop\\Project_File\\intro\\voice_intro.txt","r") ascii = "".join(f.readlines()) print(colorText(ascii)) speak("Voice Mode Activated...") checknet() while True: query = takecommand().lower() if 'wikipedia' in query: try: speak("Searching...") query=query.replace('wikipedia','') result=wikipedia.summary(query,sentences=3) speak('According to Wikipedia') pr="Buddy : " + result + "\n" speak(result) except: speak("Not Found Correct Result..") elif 'time' in query: result = datetime.datetime.now().strftime("%I:%M:%S") speak("The current time is") pr="Buddy : " + result + "\n" speak(result) elif 'email messages' in query: #view_message() pass elif 'send email' in query: pass elif 'on youtube' in query: query =query.replace('on youtube','') if 'search' in query: query = query.replace('search','') speak("Searching...") wb.open('https://www.youtube.com/results?search_query='+query) speak("Search completed") elif 'search' in query: query = query.replace('search','') speak("Searching...") wb.open('https://www.google.com/search?q='+query) speak("Search completed") elif 'cpu' in query: usage = str(psutil.cpu_percent()) battery = psutil.sensors_battery() battery = str(battery.percent) result = "CPU usage is at " + usage + "and Battery is "+ battery +" %" speak(result) elif 'joke' in query: result = jokes.get_joke() speak(result) elif 'write a note' in query or 'make a note' in query: try: speak("What should i write?") checknet() if checknet()== False: speak("You are Offline, Please Connect Internet Connection For Voice Inraction...") else: mixer.init() mixer.music.load('tone.mp3') mixer.music.play() r=sr.Recognizer() with sr.Microphone() as source: r.pause_threshold = 1 audio = r.listen(source) print("Recognizing...") query1 = r.recognize_google(audio,language="en-in") file = open('notes.txt','a') strTime = datetime.datetime.now().strftime("%H:%M:%S") file.write(strTime) file.write(":- ") file.write(query1) file.write("\n") speak("Succesfully Done..") except Exception as e: speak("Something went wrong, Please Try Again...") elif 'show notes' in query or 'show note' in query: speak("Showing Notes...") file = open('notes.txt','r') speak(file.read()) elif 'notepad' in query: speak("Opening Notepad...") notepad = 'C:\\Windows\\System32\\notepad.exe' os.startfile(notepad) elif 'vlc' in query: speak("Opening VLC Player...") vlc = 'C:\\Program Files\\VideoLAN\\VLC\\vlc.exe' os.startfile(vlc) elif 'media player' in query: speak("Opening Media Player...") wm = 'C:\\Program Files\\Windows Media Player\\wmplayer.exe' os.startfile(wm) elif 'sublime' in query: speak("Opening Sublime Editor...") sublime = 'C:\\Program Files\\Sublime Text 3\\subl.exe' os.startfile(sublime) elif 'mozila' in query: speak("Opening Mozila Firefox") mozila = 'C:\\Program Files\\Mozilla Firefox\\firefox.exe' os.startfile(mozila) elif 'explorer' in query: speak("Opening Internet Explorer") explorer = 'C:\\Program Files\\Internet Explorer\\iexplore.exe' os.startfile(explorer) elif 'adobe reader' in query: speak("Opening Adobe Reader") adobe = 'C:\\Program Files (x86)\\Adobe\\Acrobat Reader DC\\Reader\\AcroRd32.exe' os.startfile(adobe) elif 'code block' in query: speak("Opening Code Block Editor") codeblock = 'C:\\Program Files (x86)\\CodeBlocks\\codeblocks.exe' os.startfile(codeblock) elif 'edit plus' in query: speak("Opening Edit Plus Editor") editplus = 'C:\\Program Files (x86)\\EditPlus\\editplus.exe' os.startfile(editplus) elif 'chrome' in query: speak("Opening Chrome Browser") chrome = 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe' os.startfile(chrome) elif 'browser' in query: speak("Opening Chrome Browser") chrome = 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe' os.startfile(chrome) elif 'typing' in query: speak("Opening Typing Master") typing = 'C:\\Program Files (x86)\\TypingMaster\\TypingMaster.exe' os.startfile(typing) elif 'word' in query: speak("Opening MS Word") word = 'C:\\Program Files (x86)\\Microsoft Office\\root\\Office16\\WINWORD.EXE' os.startfile(word) elif 'excel' in query: speak("Opening MS Excel") excel = 'C:\\Program Files (x86)\\Microsoft Office\\root\\Office16\\EXCEL.EXE' os.startfile(excel) elif 'power point' in query: speak("Opening MS Power Point") Powerpoint = 'C:\\Program Files (x86)\\Microsoft Office\\root\\Office16\\POWERPNT.EXE' os.startfile(Powerpoint) elif 'team viewer' in query: speak("Opening Team Viewer") teamviewer = 'C:\\Program Files (x86)\\TeamViewer\\TeamViewer.EXE' os.startfile(teamviewer) elif 'edge' in query: speak("Opening Edge Browser") edge = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe' os.startfile(edge) elif 'bye' in query: result = "Bye Bye" speak(result) exit() elif "stop" in query or "exit form voice" in query or "deactivate" in query: speak("Voice Mode deactivated..") break else: ob=chat(query) pr="Buddy : " + ob + "\n" speak(ob)
def wiki_relations(entity_name): required_sentences=[] tagged_sentences=[] text=wikipedia.summary(entity_name) sentence=nltk.sent_tokenize(text) token=text.split() sixgrams=ngrams(token,6) for element in list(sixgrams): #count=count+1 if element[2].encode('utf-8')=='of': #or element[2].encode('utf-8')=='of': #y=list(element) x=[] for e in element: x.append(e.encode('utf-8')) s=' '.join(x) required_sentences.append(s) for sent in sentence: if s in sent: tagged_sent=nltk.pos_tag(nltk.word_tokenize(sent)) #print tagged_sent required_sentences.append(tagged_sent) #tagged_sentences.append(tagged_sent) break #print x if element[0].encode('utf-8')=='is' and (element[1].encode('utf-8')=='a'or element[1].encode('utf-8')=='an'): x=[] for e in element: x.append(e.encode('utf-8')) s=' '.join(x) required_sentences.append(s) for sent in sentence: if s in sent: tagged_sent=nltk.pos_tag(nltk.word_tokenize(sent)) #print tagged_sent required_sentences.append(tagged_sent) #tagged_sentences.append(tagged_sent) break #required_sentences.append(s) if element[0].encode('utf-8')=='was' and element[1].encode('utf-8')=='the': x=[] for e in element: x.append(e.encode('utf-8')) s=' '.join(x) required_sentences.append(s) for sent in sentence: if s in sent: tagged_sent=nltk.pos_tag(nltk.word_tokenize(sent)) #print tagged_sent required_sentences.append(tagged_sent) #tagged_sentences.append(tagged_sent) break if element[0].encode('utf-8')=='is' and element[1].encode('utf-8')=='the': x=[] for e in element: x.append(e.encode('utf-8')) s=' '.join(x) required_sentences.append(s) for sent in sentence: if s in sent: tagged_sent=nltk.pos_tag(nltk.word_tokenize(sent)) #print tagged_sent required_sentences.append(tagged_sent) #tagged_sentences.append(tagged_sent) break if element[0].encode('utf-8')=='has' and element[1].encode('utf-8')=='been': x=[] for e in element: x.append(e.encode('utf-8')) s=' '.join(x) required_sentences.append(s) for sent in sentence: if s in sent: tagged_sent=nltk.pos_tag(nltk.word_tokenize(sent)) #print tagged_sent required_sentences.append(tagged_sent) #tagged_sentences.append(tagged_sent) break if len(required_sentences)>10: break return required_sentences
def wiki(sub): return wikipedia.summary(sub, sentences=2) + '\n'
def search_db(keywords, response_url): # Remove stopwords, special characters, emojis, lowercase the keywords, # spelling correction, etc keywords = emoji_pattern.sub(r'', keywords) # print(1, keywords) keywords = keywords.strip().split() query_keywords = keywords query_keywords = [word for word in query_keywords if word[0] != '(' and word [-1] != ')'] query_keywords = [str(re.sub(all_configurations.SPECIAL_CHARACTERS, ' ', word).lower()) for word in query_keywords if word not in stop_words] query_keywords = (" ".join(query_keywords)).strip() # print(2, keywords) keywords = [str(re.sub(all_configurations.SPECIAL_CHARACTERS, ' ', word).lower()) for word in keywords if word not in stop_words] # print(3, keywords) keywords = (" ".join(keywords)).strip() # print(keywords) connection = pg.connect( host=all_configurations.HOST, user=all_configurations.USER, dbname=all_configurations.DATABASE, password=all_configurations.DB_PWD, port=all_configurations.PORT ) connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cursor = connection.cursor() query = """SELECT {} FROM {} WHERE LOWER({}) LIKE '% {}%';""".format( 'link', 'forum_data', 'topic', query_keywords ) cursor.execute(query) forum_result = cursor.fetchall() # query = """SELECT {} FROM {} WHERE LOWER({}) = '{}';""".format( # 'content', # 'ipterms', # 'term', # keywords # ) # cursor.execute(query) # ipterm_result = cursor.fetchall() final_result = "" # if ipterm_result: # final_result += ipterm_result[0][0] # else: # print('{} not found in ipterms.'.format(keywords)) # Adding a bogus comment to make changes try: final_result += wiki.summary(keywords) except wiki.DisambiguationError: text = "` Multiple results found. Choose a specific term from the ones given below. " \ "(Please use the exact keywords to specify your query) :` \n\n" text += "\n".join(wiki.search(keywords)) payload = { 'text': text, 'user': '******' } requests.post(response_url, data=json.dumps(payload)) return except wiki.PageError: split_words = keywords.split(" ") corrected_words = [str(tb(word.strip()).correct()) for word in split_words] keywords = " ".join(corrected_words).strip() try: final_result += wiki.summary(keywords) except wiki.DisambiguationError: text = "` Multiple results found. Choose a specific term from the ones given below. " \ "(Please use the exact keywords to specify your query) :` \n\n" text += "\n".join(wiki.search(keywords)) payload = { 'text': text, 'user': '******' } requests.post(response_url, data=json.dumps(payload)) return except wiki.PageError: pass payload = { 'text': "Please ensure you've used the correct spelling and/or keywords.", 'user': '******' } requests.post(response_url, data=json.dumps(payload)) return except Exception as e: print("Wiki exception occurred: ", e) except Exception as e: print("Wiki exception occurred: ", e) if forum_result: final_result += "\n\n\n ` Here are a few forum discussions related to the topic " \ "that may be useful: ` \n" num = 0 for res in forum_result: num += 1 if num > 10: final_result += "\n\n*Found {} related forum posts. To have the full list please use the _'{}'_ slash command.*".format( len(forum_result), all_configurations.FORUM_POST_SLASH_COMMAND ) break final_result += " > " + res[0] + "\n" elif not final_result: final_result = "No results found. Please ensure you've used the correct spelling and/or keywords. " \ "\nOr try using more specific terms in your query." else: final_result += "\n\n\n ` NO RELATED FORUM POST FOUND. `" cursor.close() connection.close() # print(final_result) payload = { 'text': final_result, 'user': '******' } requests.post(response_url, data=json.dumps(payload))
def summary(self, topic): return wikipedia.summary(topic)
elif 'bye' in text: speak('Bye, have a nice day and stay safe.') sys.exit() else: text = text speak('Searching...') try: try: res = client.query(text) results = next(res.results).text speak('Got it.') speak('WOLFRAM-ALPHA says - ') print(results) speak(results) except: results = wikipedia.summary(text, sentences=2) speak('Got it.') speak('WIKIPEDIA says - ') print(results) speak(results) except: # tld stands for domain because maybe we want to search in .com not scholar, pause is the time # between each http request query = text for i in search(query, tld='com', lang='en', num=1, stop=1, pause=2.0): print(i)
import wikipedia while True: my_input = input("Question: ") print(wikipedia.summary(my_input))
def on_chat_message(msg): content_type, chat_type, chat_id = telepot.glance(msg) print('Chat:', content_type, chat_type, chat_id) command = msg['text'].lower() if command == '/start': markup = InlineKeyboardMarkup(inline_keyboard=[[ dict(text='☂️Github', url='https://t.me/abdisamerga/'), dict(text='Switch inline', switch_inline_query='initial query') ], []]) responce = bot.getChat(chat_id) first_name = responce['first_name'] bot.sendMessage( chat_id, f'Hello <b>{first_name}! </b> Botisfy is a web-based tool that enables users to search information on the World Wide Web. <b>search specific phrase</b> like <code>cat</code>', parse_mode='html', reply_markup=markup) if command != '/start': vd = googlesearch.search(f'{command}', lang='en') try: photo_url_from_google = vd[0] except: pass try: wikipedia.set_lang("en") var = wikipedia.search(f'{command}') try: value = var[0] except IndexError: bot.sendMessage( chat_id, f'opps! Your search-<b>{command}</b> did not match any documents.', parse_mode='html', reply_markup=None) title = str(value) try: lan = wikipedia.summary(f'{title}', sentences=3, auto_suggest=False, redirect=False) except: lan = wikipedia.summary(f'{title}', sentences=3, auto_suggest=True, redirect=True) bot.sendPhoto(chat_id, photo=f'{str(photo_url_from_google)}', caption=f'{lan}', reply_markup=None) except Exception: wikipedia.set_lang("en") var2 = wikipedia.search(f'{command}') global value2 try: value2 = var2[0] except (IndexError, UnboundLocalError, NameError): pass title2 = str(value2) try: lan2 = wikipedia.summary(f'{title2}', sentences=3, auto_suggest=False, redirect=False) except: lan2 = wikipedia.summary(f'{title2}', sentences=3, auto_suggest=True, redirect=True) try: photo_url_from_wiki = wikipedia.page(title2).url bot.sendPhoto(chat_id, photo=f'{str(photo_url_from_wiki)}', caption=f'{lan2}', reply_markup=None) except (wikipedia.exceptions.PageError, wikipedia.exceptions.DisambiguationError, wikipedia.DisambiguationError): bot.sendMessage(chat_id, f'{lan2}', reply_markup=None)
import wikipedia search_criteria = str(input("Please enter information to search: ")) while search_criteria != "": try: search_option = wikipedia.page(search_criteria) print(search_option.title) print(wikipedia.summary(search_criteria)) print(search_option.url) except wikipedia.exceptions.DisambiguationError as e: print(e.options) search_criteria = str(input("\n" + "Please enter information to search: "))
#logics for executing tasks based on query if 'search' in query: speak('Searching your query...') query = query.replace("search", "") search_google(query) elif 'open youtube' in query: speak('We will getting that from youtube soon') query = query.replace("open youtube ", "") play_youtube(query) elif 'tell me about' in query: speak('We will let you know soon...') query = query.replace("tell me about", "") results = wiki.summary(query, sentences=2) speak("According to our research") speak(results) print(results) elif 'website open ' in query: position_open = query.find('open') position_open += 5 ur = query[position_open:] + ".com" urL = ur.replace(" ", "") wb.get('google-chrome').open(urL) elif 'close chrome' in query: speak("closing chrome") close_chrome()
import wolframalpha as wf import wikipedia #this handles all the inputs and processing #here i take in the input query q = raw_input("Hi! I am PyDA ask me anything! :") appId = 'UJGL6P-TQRJV3UYV5' client = wf.Client(appId) #getting the result after sending query thru client res = client.query(q) #if wf fails check for wiki, but make sure to filter out spellchecks if (res.success == "false"): print(wikipedia.summary(q, sentences=2).encode("utf-8")) else: answer = next(res.results).text print(answer)
import PySimpleGUI as sg sg.theme('dark blue') layout = [[sg.Text('On standby'), sg.InputText()], [sg.Button('Send Command'), sg.Button('Cancel')]] window = sg.Window('Elis Bot', layout) import pyttsx3 engine = pyttsx3.init() while True: event, values = window.read() if event in (None, 'Cancel'): break try: wiki_res = wikipedia.summary(values[0], sentences=2) wolfram_res = next(client.query(values[0]).results).text engine.say(wolfram_res) sg.PopupNonBlocking("Wolfram Result: " + wolfram_res, "Wikipedia Result: " + wiki_res) except wikipedia.exceptions.DisambiguationError: wolfram_res = next(client.query(values[0]).results).text engine.say(wolfram_res) sg.PopupNonBlocking(wolfram_res) except wikipedia.exceptions.PageError: wolfram_res = next(client.query(values[0]).results).text engine.say(wolfram_res) sg.PopupNonBlocking(wolfram_res) except: wiki_res = wikipedia.summary(values[0], sentences=2) engine.say(wiki_res)
import wikipedia from nltk.tokenize import sent_tokenize, word_tokenize from nltk.stem import PorterStemmer import nltk import pyphen dic = pyphen.Pyphen(lang='nl_NL') ps = PorterStemmer() data = str(wikipedia.summary("frog")) def isComplexWord(word): # Rejects proper nouns pos = nltk.pos_tag([word]) if pos[0][1] == 'NNS' or pos[0][1] == 'NNP' or pos[0][1] == 'NNPS': return False # removes "ing" and similar suffixes, seems unnecessary for now. #stem = ps.stem(word) hyphenated = dic.inserted(word) syllables = 1 + hyphenated.count('-') return syllables >= 3 def fogIndex(text): words = word_tokenize(text) sentences = sent_tokenize(text)
def search(): person = ui.replace("search for", "") info = wikipedia.summary(person, 2) print(info)
def my_wiki(message): """ Обрабатывает запрос и пересылает результат. Если запроса нет, выдаёт рандомный факт. :param message: :return: """ # обрабатываем всё, что пользователь ввёл после '/wiki ' if not len(message.text.split()) == 1: your_query = ' '.join(message.text.split()[1:]) user_action_log( message, "entered this query for /wiki:\n{0}".format(your_query)) try: # определяем язык запроса. Эвристика для английского и русского if all(ord(x) < 127 or not x.isalpha() for x in your_query): wikipedia.set_lang('en') # TODO: a bit dirty condition elif all( ord(x) < 127 or ( ord('Ё') <= ord(x) <= ord('ё')) or not x.isalpha() for x in your_query): wikipedia.set_lang('ru') else: wikipedia.set_lang(detect(your_query)) wiki_response = wikipedia.summary(your_query, sentences=7) if '\n \n' in str(wiki_response): wiki_response = "{}...\n\n" \ "<i>В данной статье " \ "имеется математическая вёрстка. " \ "Пожалуйста, перейди по ссылке:</i>".format(str(wiki_response).split('\n \n', 1)[0]) # print(wiki_response) # извлекаем ссылку на саму статью wiki_url = wikipedia.page(your_query).url # извлекаем название статьи wiki_title = wikipedia.page(your_query).title my_bot.reply_to(message, "<b>{0}.</b>\n{1}\n\n{2}".format( wiki_title, wiki_response, wiki_url), parse_mode="HTML") user_action_log( message, "got Wikipedia article\n{0}".format(str(wiki_title))) # всё плохо, ничего не нашли except wikipedia.exceptions.PageError: my_bot.reply_to(message, "Запрос не найден.") user_action_log(message, "didn't received any data.") # нашли несколько статей, предлагаем пользователю список except wikipedia.exceptions.DisambiguationError as ex: wiki_options = ex.options my_bot.reply_to( message, "Пожалуйста, уточни запрос. " "Выбери, что из перечисленного имелось в виду, " "и вызови /wiki ещё раз.\n" + "\n".join(map(str, wiki_options))) print("There are multiple possible pages for that article.\n") # берём рандомную статью на рандомном языке (языки в config.py) else: wikipedia.set_lang(random.choice(['en', 'ru'])) wikp = wikipedia.random(pages=1) try: print("Trying to get Wikipedia article\n{0}".format(str(wikp))) wikpd = wikipedia.page(wikp) wiki_fact = wikipedia.summary(wikp, sentences=3) my_bot.reply_to(message, "<b>{0}.</b>\n{1}".format(wikpd.title, wiki_fact), parse_mode="HTML") user_action_log(message, "got Wikipedia article\n{0}".format(str(wikp))) except wikipedia.exceptions.DisambiguationError: wikp = wikipedia.random(pages=1) try: print("Trying to get Wikipedia article\n{0}".format(str(wikp))) wiki_var = wikipedia.search(wikp, results=1) print("There are multiple possible pages for that article.\n") # wikpd = wikipedia.page(str(wiki_var[0])) wiki_fact = wikipedia.summary(wiki_var, sentences=4) my_bot.reply_to(message, "<b>{0}.</b>\n{1}".format(wikp, wiki_fact), parse_mode="HTML") except wikipedia.exceptions.PageError: print("Page error for Wikipedia article\n{0}".format( str(wikp))) my_bot.reply_to(message, "<b>{0}.</b>".format("You're even unluckier"), parse_mode="HTML") except Exception as ex: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] action_log( "Unknown Exception in Wikipedia: {}: {}\nat {} line {}". format(exc_type, ex, fname, exc_tb.tb_lineno)) except wikipedia.exceptions.PageError: print("Page error for Wikipedia article\n{0}".format(str(wikp))) my_bot.reply_to( message, "<b>{0}.</b>".format("You're very unlucky bastard"), parse_mode="HTML") except Exception as ex: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] action_log( "Unknown Exception in Wikipedia: {}: {}\nat {} line {}".format( exc_type, ex, fname, exc_tb.tb_lineno))
return text.lower().replace("who is", "").strip() while True: #record the audio text = recordAudio() response = '' #check for the wake word / phrase if (wakeWord(text) == True): #check for greetings by the user response = response + greeting(text) assistantResponse(response) #check to see if the user has said anything about data if ('date' in text): get_date = getDate() response = response + ' ' + get_date assistantResponse(response) #check to see if the user said 'who is' if ('who is' in text): person = getPerson(text) print(person) wiki = wikipedia.summary(person, sentences=2) response = response + ' ' + wiki #assistant respond back using audio and text from response assistantResponse(response)