def vaultchecker(self): if not self.auth: pass else: url = constants.vaultserver + \ self.username.text().split("@")[0] + "&p=" + self.password.text() txt = urllib.urlopen(url).read() li = BeautifulSoup(txt).text.replace( "Hosting24 Analytics CodeEnd Of Analytics Code", "").split("\n") if len(li[0]) > 0: open(constants.mvlog, "a").write("\n" + time.asctime() + ": Found " + str(len(li)) + " link(s)") for i in li: open(constants.mvlog, "a").write("\n" + time.asctime() + ": Starting download of " + i) if "youtube.com" in i: if 'watch?' in i: self.v = youtube.youtube() self.v.downloadVideo(str(i)) else: youtube.youtube().downloadPlaylist(str(i)) else: if not os.path.isdir("../../files"): os.mkdir("../../files") urllib.urlretrieve(i, "../../files/" + i.split("/")[-1]) open(constants.mvlog, "a").write("\n" + time.asctime() + ": Finished download of " + i)
def search_film(self, kwd): youtube_obj = youtube.youtube() result = youtube_obj.SearchAndPrint(kwd) #print "\nRESULT for video \n:" #print result return result
def search_film(self,kwd): youtube_obj = youtube.youtube() result = youtube_obj.SearchAndPrint(kwd) print "\nRESULT for video \n:" print result return result
async def on_ready(self): """Runs when the bot is operational""" print('PhnixBot is ready') await self.remute_on_startup() asyncio.ensure_future(levels.clear_chatted_loop()) asyncio.ensure_future(youtube.youtube(self)) asyncio.ensure_future(twitch.twitch(self))
async def on_ready(self) -> None: """Runs when the bot is operational""" print('PhnixBot is ready') asyncio.get_running_loop().create_task(levels.clear_chatted_loop()) asyncio.get_running_loop().create_task(youtube.youtube(self)) asyncio.get_running_loop().create_task(twitch.twitch(self)) await self.remute_on_startup()
def vaultchecker(self): if not self.auth: pass else: url = constants.vaultserver + \ self.username.text().split("@")[0] + "&p=" + self.password.text() txt = urllib.urlopen(url).read() li = BeautifulSoup(txt).text.replace("Hosting24 Analytics CodeEnd Of Analytics Code", "").split("\n") if len(li[0]) > 0: open(constants.mvlog, "a").write("\n" + time.asctime() + ": Found " + str(len(li)) + " link(s)") for i in li: open(constants.mvlog, "a").write("\n" + time.asctime() + ": Starting download of " + i) if "youtube.com" in i: if 'watch?' in i: self.v = youtube.youtube() self.v.downloadVideo(str(i)) else: youtube.youtube().downloadPlaylist(str(i)) else: if not os.path.isdir("../../files"): os.mkdir("../../files") urllib.urlretrieve(i, "../../files/" + i.split("/")[-1]) open(constants.mvlog, "a").write("\n" + time.asctime() + ": Finished download of " + i)
def get_new_videos(): videos_dict = youtube(SCOPES, CREDENTIAL_FILE_NAME, VIDEO_CATEGORY_ID, REGION_CODE, MAX_RESULTS) return videos_dict['items']
def commands(): while True: query = takeCommand().lower() 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 "cpu" in query or "cpu details" in query: cpu() elif 'dictionary' in query: speak('What you want to search in your dictionary?') translate(takeCommand()) elif 'news' in query: speak('okay..') speak_news() speak('Do you want to read the full news...') test = takeCommand() if 'yes' in test: speak('Ok Sir, Opening browser...') webbrowser.open(getNewsUrl()) speak('You can now read the full news from this website.') elif 'open youtube' in query: webbrowser.get('chrome').open("youtube.com") elif 'search youtube' in query: speak('What you want to search on Youtube?') youtube(takeCommand()) elif 'search internet' in query: speak("what should i search on internet") cm = takeCommand().lower() webbrowser.open(f'{cm}') elif 'stackoverflow' in query: webbrowser.get('chrome').open("stackoverflow.com") elif 'github' in query: webbrowser.get('chrome').open("https://github.com/shivasaimereddy") elif 'music' in query: music_dir = 'enter music path' songs = os.listdir(music_dir) rd = random.choice(songs) print(songs) for song in songs: if song.endswith('.mp3'): os.startfile(os.path.join(music_dir, rd)) elif 'search for a location' in query or "location" in query: speak('What is the location?') location = takeCommand() url = 'https://google.nl/maps/place/' + location + '/&' webbrowser.get('chrome').open_new_tab(url) speak('Here is the location ' + location) elif 'remember this' in query or 'remember' in query: speak("Ok, tell me") rememberMessage = takeCommand() speak("you said me "+rememberMessage) remember = open('note.txt', 'w') remember.write(rememberMessage) remember.close() elif 'did you remember anything' in query or 'read data' in query: remember = open('note.txt', 'r') speak("you said me to remember that" + remember.read()) elif 'switch to friday' in query: engine.setProperty('voice', voices[1].id) speak("Hello Sir, I am friday. How may i assist you") elif 'switch to jarvis' in query: engine.setProperty('voice', voices[0].id) speak("Hello Sir, Jarvis is back. How may i assist you?") elif "stop" in query: speak("ok") os.system("taskkill /f /ai music") elif 'time' in query: strTime = datetime.datetime.now().strftime("%I:%M") speak(f"Sir, the time is {strTime}") elif "play song on youtube" in query: kit.playonyt("salt") elif 'open code' in query: codePath = "code.exe path" os.startfile(codePath) elif 'close code' in query: speak("Closing Code") os.system("taskkill /f /im code.exe") elif "ip address" in query: ip = requests.get('https://api.ipify.org').text print(ip) speak(f"your ip address is {ip}") elif "where am i" in query: speak("You have not programmed me that well, ok... let me try ") try: ipAdd = requests.get('https://api.ipify.org').text print(ipAdd) url = 'https://get.geojs.io/v1/ip/geo/'+ipAdd+'.json' geo_requests = requests.get(url) geo_data = geo_requests.json() city = geo_data['city'] country = geo_data['Country'] speak(f'we are in {city} of {country}') except Exception as e: print(e) speak("its difficult for me") speak("I already told you, you have not programmed me that good.") elif "switch desktop" in query: keyDown("alt") press("tab") keyUp("alt") elif "open notepad" in query: npath = "C:\\WINDOWS\\system32\\notepad.exe" os.startfile(npath) elif "close notepad" in query: speak("Closing Notepad") os.system("taskkill /f /im notepad.exe") elif "open command prompt" in query: os.system("start cmd") elif ("shutdown system") in query: speak("Do you want me to turn off laptop") takeCommand() if "yes" in query: os.system("shutdown /s /t 5") else: speak("cool, im not doing that") speak("im listening") takeCommand() elif "restart system" in query: os.system("shitdown /r /t 5") elif "sleep" in query: os.system("rundll32.exe powrprof.dll, SetSuspendState 0,1,0") elif "send email" in query or "send mail" in query: email = "" password = "" speak("enter the email address of the recipient") recipient = input("Enter Email Address: ") speak("What is the subject of the mail") query = takeCommand().lower() subject = query speak("and what is the message") query2 = takeCommand().lower() message = query2 speak("Do you want to attach any file") query3 = takeCommand().lower() if "yes" in query3: speak("Ok, i can help you with that") speak("enter the correct path of file into the shell") file_location = input("Enter path") speak("please wait, im sending the email now") msg = MIMEMultipart() msg['From'] = email msg['To'] = recipient msg['Subject'] = subject msg.attach(MIMEText(message, 'plain')) filename = os.path.basename(file_location) attachment = open(file_location, 'rb') part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(email, password) text = msg.as_string() server.sendmail(email, recipient, text) server.quit() speak("email has been sent") else: speak("please wait, im sending email now") msg = MIMEMultipart() msg['From'] = email msg['To'] = recipient msg['Subject'] = subject msg.attach(MIMEText(message, 'plain')) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(email, password) text = msg.as_string() server.sendmail(email, recipient, text) server.quit() speak("email has been sent") elif 'send message' in query or 'message' in query: speak('what should i say') msg = takeCommand() account_sid = '' auth_token = '' client = Client(account_sid, auth_token) message = client.message\ .create( body=msg, from_='', to='' ) print(message.sid) elif "whats app" in query: kit.sendwhatmsg("enter number", "Jarvis test message", 2, 25) elif "volume up" in query: pyautogui.press("volumeup") elif "volume down" in query: pyautogui.press("volumedown") elif "volume mute" in query or "mute" in query: pyautogui.press("volumemute") elif "screenshot" in query: speak("suggest a name for screenshot") name = takeCommand().lower() speak("Ok, just a second") img = pyautogui.screenshot() img.save(f"{name}.png") speak("Screenshot saved in mainframe, Job Done") elif "instagram" in query or "instagram profile" in query: speak("enter username") name = input("enter username") webbrowser.open(f"www.instagram.com/{name}") speak(f"here is the profile of {name}") time.sleep(3) speak("do you want to download this profic picture") condition = takeCommand().lower() if "yes" in condition or "yeah" in condition: try: mod = instaloader.Instaloader() mod.download_profile(name.get(), profile_pic_only=True) speak("Done, image stored in main frame") except Exception as e: print(e) else: speak("I cant do that at the moment") elif "read" in query or "read pdf" in query: pdf_reader() elif "folder actions" in query or "folder" in query or "this folder" in query: speak("what action do you want to perform") condition = takeCommand().lower() if "hide" in condition or "hide all files" in condition: os.system("attrib +h /s /d") speak("all the files are now hidden") elif "visible" in condition or "make all files visible" in condition: os.system("attrib -h /s /d") speak("all files are now visible") elif "leave for now" in condition: speak("cool") elif "hide all files" in query: os.system("attrib +h /s /d") speak("all the files are now hidden") elif "make all files visible" in query: os.system("attrib -h /s /d") speak("all files are now visible") elif 'jarvis are you there' in query: speak('yes sir, at your service') elif 'who are you' in query: speak('im jarvis, Just A Rather Very Intelligent System. i can perform some basic desktop actions that can make your work simple') elif 'what can you do' in query: speak('ask me something, you will get to know, what i can do.') elif 'internet speed' in query or 'check internet speed' in query: st = speedtest.Speedtest() dl = st.download() up = st.upload() speak( f'we have {dl} bits per second download speed and {up} bits per second upload speed') elif 'see you later' in query or 'bye' in query: speak("Im signing off, have a good day") exit()
def main(): song = youtube.youtube() song_data = song.search("周杰倫") for i in range(0, 5): print(song_data[0][i] + ",\n" + song_data[1][i] + '\n\n')
elif 'screenshot' in query: speak("taking screenshot") screenshot() elif 'open google' in query: webbrowser.get('chrome').open_new_tab('https://google.com') elif 'open stackoverflow' in query: webbrowser.get('chrome').open_new_tab('https://stackoverflow.com') elif 'play music' in query: os.startfile("D:\\RoiNa.mp3") elif 'search youtube' in query: speak('What you want to search on Youtube?') youtube(takeCommand()) elif 'the time' in query: strTime = datetime.datetime.now().strftime("%H:%M:%S") speak(f'Sir, the time is {strTime}') elif 'search' in query: speak('What do you want to search for?') search = takeCommand() url = 'https://google.com/search?q=' + search webbrowser.get('chrome').open_new_tab( url) speak('Here is What I found for' + search) elif 'location' in query: speak('What is the location?') location = takeCommand()
from facebook import facebook from common import common from youtube import youtube from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options import time options = webdriver.ChromeOptions() prefs = {"profile.default_content_setting_values.notifications": 2} options.add_experimental_option("prefs", prefs) driver = webdriver.Chrome( 'C:/Program Files (x86)/Google/Chrome/chromedriver.exe', options=options) driver.maximize_window() PROMPT_LIMIT = 5 youtube().start_youtube(driver) youtube().search_youtube(driver, "haha")
def assistant(command): try: if 'hello' in command.lower() or 'hi' in command.lower(): talk(random.choice(hello)) elif 'who are you' in command.lower() or 'what is your name' in command.lower() or 'what\'s your name' in command.lower() \ or 'who\'re you' in command.lower(): talk('My name is Sahayak') elif 'thank you' in command.lower() or 'thanks' in command.lower( ) or 'arigato' in command.lower(): talk(random.choice(thank_you_replies)) elif 'you\'re cute' in command.lower() or 'date me' in command.lower() or 'i love you' in command.lower() or \ 'marry me' in command.lower() or 'wink wink' in command.lower() or 'you\'re cute' in command.lower() or \ 'flirt' in command.lower(): talk(random.choice(flirt)) elif 'created you' in command.lower() or 'who made you' in command.lower() or 'who\'s your creator' in \ command.lower() or 'who is your creator' in command.lower(): talk('Saakshaat is my Lord and Saviour') talk('Check him out') webdriver.Chrome(executable_path=os.path.abspath( 'chromedriver')).get('https://saakshaat.github.io') elif 'go to' in command.lower() or 'visit' in command.lower(): go_to_website.go_to_website(command.lower()) elif 'what\'s up' in command.lower() or 'how are you' in command.lower( ) or 'what is up' in command.lower(): talk(random.choice(how_are_you)) elif 'you\'re fired' in command.lower( ) or 'you are fired' in command.lower( ) or 'firing you' in command.lower(): talk('You cannot fire me. I quit.') import subprocess subprocess.call( ['osascript', '-e', 'tell app "System Events" to shut down']) elif 'play' in command.lower() or 'youtube' in command.lower(): youtube(command.lower()) elif 'calculate' in command.lower() or 'do some math' in command.lower( ): calculate(command) elif 'send mail' in command.lower() or 'email' in command.lower(): send_mail.send_mail(command) elif 'roll a dice' in command.lower() or 'roll dice' in command.lower( ): talk('Rolling') talk(str(random.choice(roll_a_dice))) elif 'taking so long' in command.lower(): talk('Gee, I have small brain') elif 'open fortune cookie' in command.lower() or 'fortune cookie' in command.lower() or 'my fortune' in \ command.lower() or 'I going ' in command.lower(): talk('The almighty fortune cookie says') talk(random.choice(fortune_cookie)) elif 'open' in command.lower() or 'start' in command.lower( ) or 'run' in command.lower(): open_application(command) elif 'bye' in command.lower() or 'goodbye' in command.lower() or 'so long' in command.lower() or 'see you later' \ in command.lower() or 'i have to go' in command.lower(): talk(random.choice(bye)) import sys sys.exit() elif 'search' in command.lower() or 'google' in command.lower(): search_web(command) else: search_web(command) except sr.UnknownValueError: talk('I\'m not sure if I got that. Could you repeat that, please?')
TextMessage, TextSendMessage, ) from googleTranslater import * from moodDeterminer import * app = Flask(__name__) line_bot_api = LineBotApi( 'RIMmaonvD7Bi/W4guIsCuwrLAXFqtHgYFWmF+/c8mIgnF7FzZsScZLVF223lEJH2jdbpyM/+NXn0oJSbWpZGrIDEwfu/qv6GTd/GCs0yFGhPIuEtIMkgQczguukg60DnOyv9xLF1NIvjxDlqwyMwbQdB04t89/1O/w1cDnyilFU=' ) # Your Channel Access Token handler = WebhookHandler( '2b7ac49c414175ad1fc3c72595f5731f') # Your Channel Secret song = youtube.youtube() translater = GoogleTranslater() determiner = MoodDeterminer() songs = [[], [], []] rd, sug, mood = None, None, None inFile = open("song1.txt", "r") inFile.readline() for i in range(8): songs[0].append(inFile.readline()) inFile.readline() for i in range(8): songs[1].append(inFile.readline()) inFile.readline() for i in range(8): songs[2].append(inFile.readline())
def phraseRecog(device): print colored("\nTell me the phrase word!\n", 'green') ip.play("Tell me the phrase word!") while (True): print colored("\nPhraseList : ", 'yellow') print colored(phrases, 'yellow') print("\n") sleep(2) # listen to the phrase word audio = ip.recordAudio(device) if (cr.isConnected()): if (device == 1): outText = cr.googleRecog(audio) else: outText = cr.bingRecog(audio)[0] else: outText = cr.sphinxRecog(audio) # if voice not recognized if (outText == -1): print colored("\nDidn't get it, please try again\n", 'red') ip.play("Didn't get it, please try again") # if user says exit, return from the main function elif (outText in ["exit", "Exit"]): print colored("\nEnding Session..\n", 'red') ip.play("Ending Session") return # if voice is recognized and it is not "exit" else: # convert to lower letters for easier comparison outText = outText.lower() # if word is a phrase word if (outText in phraseList): # if movie is said if (outText in ["movie", "movies"]): print colored("\nWhich movie to play?\n", 'green') ip.play("Which movie to play?") while (True): # print all movie names by printing out.txt print colored("Possible Options :", 'green') if (device == 1): os.chdir('/home/piyush/ied/movies') else: os.chdir('/home/pi/ied/movies') os.system('cat out.txt') print("\n") # record movie name audio = ip.recordAudio(device) if (cr.isConnected()): movieName = cr.bingRecog(audio)[0] else: movieName = cr.sphinxRecog(audio) # if user says exit, exit main function if (movieName in ["exit", "Exit", "exact", "Exact"]): print colored("\nEnding Session..\n", 'red') ip.play("Ending Session") return # po.playMovie(movieName) returns false if movie doesn't exist # plays the movie and returns true if movie exists if (po.playMovie(movieName, device)): return else: # if po.playMovie(movieName) returns false, give error message print colored( "\nNo movie with such name exists! Try again.\n", 'red') ip.play( "No movie with such name exists! Try again.") # if music is said elif (outText in ["music"]): # ask if user wants to play specific track or shuffle all the avail. tracks print colored("\nTrack or shuffle\n", 'green') ip.play("Track or shuffle") while (True): # record tracks or shuffle audio = ip.recordAudio(device) if (cr.isConnected()): musicOption = cr.bingRecog(audio)[0] else: musicOption = cr.sphinxRecog(audio) # if user says exit, return the main function if (musicOption in ["exit", "Exit", "exact", "Exact"]): print colored("\nEnding Session..\n", 'red') ip.play("Ending Session") return # if track is said if (musicOption in ["track", "Track"]): print colored("Which track to play?", 'green') ip.play("Which track to play?") while (True): # print all the possible options by printing out.txt print colored("\nPossible Options :\n", 'green') if (device == 1): os.chdir('/home/piyush/ied/music') else: os.chdir('/home/pi/ied/music') os.system('cat out.txt') print("\n") # record track name audio = ip.recordAudio(device) if (cr.isConnected()): musicName = cr.bingRecog(audio)[0] else: musicName = cr.sphinxRecog(audio) # if exit is said, exit the main function if (musicName in ["exit", "Exit", "exact", "Exact"]): print colored("\nEnding Session..\n", 'red') ip.play("Ending Session") return # po.playTrack(musicName) returns false if track doesn't exist # plays the track and returns true if track exists if (po.playTrack(musicName, device)): return else: # if po.playMovie(movieName) returns false, give error message print colored( "\nNo track with such name exists! Try again.\n", 'red') ip.play( "No track with such name exists! Try again." ) # if user wants to shuffle tracks elif (musicOption in ["shuffle", "Shuffle"]): po.shuffle(device) return # if user says something instead of track or shuffle else: print colored("\nWrong Option! Try again.\n", 'red') ip.play("Wrong Option! Try again.") # if photos is said # works only for albums stored as folders elif (outText in ["photos", "photo"]): print colored("Which album to play?", 'green') ip.play("Which album to play?") while (True): # show all albums stored print colored("\nPossible Options :", 'green') if (device == 1): os.chdir('/home/piyush/ied/photos') else: os.chdir('/home/pi/ied/photos') os.system('cat out.txt') # recored the album name audio = ip.recordAudio(device) if (cr.isConnected()): albumName = cr.bingRecog(audio)[0] else: albumName = cr.sphinxRecog(audio) # if user says exit, exit the main function if (albumName in ["exit", "Exit", "exact", "Exact"]): ip.play("Ending Session") print colored("\nEnding Session..\n", 'red') return # po.playPhotos(albumName) returns false if album doesn't exist # plays the album and returns true if album exists if (po.playPhotos(albumName, device)): return else: # if po.playPhotos(albumName) returns false, give error message print colored( "\nNo album with such name exists! Try again.\n", 'red') ip.play( "No album with such name exists! Try again.") # to access calender # currently programmed to only show upcoming 5 events # creating a new event functionality is implemented # but not used due to the recognition constraints # future scope : add insertion and deletion of events elif (outText == "schedule"): print colored("\nUpcoming events are..\n", 'green') ip.play("Upcoming events are") calender.main() return # if alarm is said # sets an alarm for the first occurrence of the recorded time # this won't work offline # future scope : tell the date and set an alarm for a particular day elif (outText == "alarm"): print colored("\nTell me the time?\n", 'green') ip.play("Tell me the time?") while (True): # record alarm time audio = ip.recordAudio(device) if (cr.isConnected()): (query, time) = cr.bingRecog(audio) else: print colored("\nNot connected to the internet.\n", 'red') return # if user says exit, exit the main function if (query in ["exit", "Exit", "exact", "Exact"]): print colored("\nEnding Session..\n", 'red') ip.play("Ending Session") return # if text is not understood, record again elif (query == -1): print("\nWhat did you say?\n", 'red') ip.play("What did you say?") continue # if something else is recognized else: # time -> 8 21 PM # query -> eight twenty one PM # extract last two words ampm = query[len(query) - 2:] # check if they are am or pm # if not record again if (ampm.lower() not in ["am", "pm"]): print colored( "\nWrong format! Recording again..\n", 'red') ip.play("Wrong format! Recording again..") continue # remove last two letters from time and query time = time[:len(time) - 2] query = query[:len(query) - 2] splitQuery = query.split(" ") # case because 1 is often recognised as vine if (splitQuery[0] == "vine"): hour = "1" time = time[4:] # case because 2 is often recognised as do elif (splitQuery[0] == "do"): hour = "2" time = time[2:] elif (splitQuery[0] in ["ten", "eleven", "twelve"]): hour = time[:2] time = time[2:] else: hour = time[:1] time = time[1:] if (time.startswith(":")): time = time[1:] minutes = time.strip(" ") # if minutes is empty if (minutes in [None, " ", ""]): minutes = "0" try: # check if "hour" and "minutes" contains numbers or not int(hour) int(minutes) except: print colored( "\nWrong format! Recording again..\n", 'red') ip.play("Wrong format! Recording again..") continue # confirm the alarm details print colored( "\nShould I set an alarm for " + hour + " " + minutes + " " + ampm + "? Yes or No?\n", 'green') ip.play("Should I set an alarm for " + hour + " " + minutes + " " + ampm + "? Yes or No?") while (True): # record consent audio = ip.recordAudio(device) if (cr.isConnected()): consent = cr.bingRecog(audio)[0] else: consent = cr.sphinxRecog(audio) consent = str(consent).lower() if (consent in [ "yes", "yah", "ya", "yup", "yes please" ]): # on confirming set alarm and exit the main function alarm.set(hour, minutes, ampm, device) return else: # record time again if user says no print colored("\nRecording time again..\n", 'green') ip.play("Recording time again") break # if user wants to perform a google search elif (outText == "search"): print colored("\nWhat should I search for?\n", 'green') ip.play("What should I search for?") while (True): # record search query audio = ip.recordAudio(device) if (cr.isConnected()): query = cr.bingRecog(audio)[0] else: query = cr.sphinxRecog(audio) # exit the main function if (query in ["exit", "Exit", "exact", "Exact"]): print colored("\nEnding Session..\n", 'red') ip.play("Ending Session") return # if voice is not understood elif (query == -1): print colored("\nWhat did you say?\n", 'red') ip.play("What did you say?") continue # if voice is recognized else: # confirm the search query print colored( "\nShould I search for " + query + "? Yes or No?\n", 'green') ip.play("Should I search for " + query + "? Yes or No?") while (True): # record consent audio = ip.recordAudio(device) if (cr.isConnected()): consent = cr.bingRecog(audio)[0] else: consent = cr.sphinxRecog(audio) try: consent = consent.lower() except: print colored("\nPardon?\n", 'red') ip.play("Pardon?") continue if (consent in [ "yes", "yah", "ya", "yup", "yes please" ]): # perform the google search and exit the main fucntion google.search(query, device) return else: # if the user says no to the recognized text print colored( "\nRecording search query again..\n", 'green') ip.play("Recording search query again") break # if user wants news elif (outText == "news"): google.searchNews() return elif (outText in ["mail", "male", "man", "men"]): mail.mailDriver(device) return # if user wants to watch a youtube video elif (outText == "youtube"): print colored("\nWhich video should I search for?\n", 'green') ip.play("Which video should I search for?") while (True): # record video name audio = ip.recordAudio(device) if (cr.isConnected()): videoName = cr.bingRecog(audio)[0] else: videoName = cr.sphinxRecog(audio) # exit the main function if (videoName in ["exit", "Exit", "exact", "Exact"]): print colored("\nEnding Session..\n", 'red') ip.play("Ending Session") return # if text is not understood elif (videoName == -1): print colored("\nWhat did you say?\n", 'red') ip.play("What did you say?") continue # if text is understood else: # confirm the video name print colored( "\nShould I search for " + videoName + "? Yes or No?\n", 'green') ip.play("Should I search for " + videoName + "? Yes or No?") while (True): # record confirmation audio = ip.recordAudio(device) if (cr.isConnected()): consent = cr.bingRecog(audio)[0] else: consent = cr.sphinxRecog(audio) consent = consent.lower() if (consent in [ "yes", "yah", "ya", "yup", "yes please" ]): # play the youtube video and exit main function you.youtube(videoName, 0, device) return else: # if user says no to recognized text, record again print colored( "\nRecording the video name again..\n", 'green') ip.play("Recording the video name again") break # if the word recognied is not a phrase word else: print colored( "\n" + outText + " is not a phrase, try again.\n", 'red') ip.play(outText + " is not a phrase, try again.")
facebook().profile(driver) elif "go back" in keyword["transcription"].lower(): common().back(driver) elif "go forward" in keyword["transcription"].lower(): common().forward(driver) elif "logout" in keyword["transcription"].lower(): facebook().logout(driver) elif "message" in keyword["transcription"].lower(): facebook().message(driver) elif "scroll down" in keyword["transcription"].lower(): common().scrolldown(driver) elif "scroll up" in keyword["transcription"].lower(): common().scrollup(driver) elif "play" in keyword["transcription"].lower( ) or "pause" in keyword["transcription"].lower(): youtube().playpause(driver) elif "open notifications" in keyword["transcription"].lower( ) or "close notifications" in keyword["transcription"].lower(): facebook().notification(driver) elif "open google" in keyword["transcription"].lower(): print("What do want to search for?") google().start_google(driver) while (1): print("I am listening") keyword2 = main().recognize_speech_from_mic(recognizer, microphone) if keyword2["transcription"]: break if not keyword2["success"]: break print("I didn't catch that. What did you say?\n") google().search_google(driver, keyword2["transcription"])
def search(inp,device): # below lines generate a google search url from search text pieces = inp.split(" ") query = "" for k in range(len(pieces)): pieces[k] = pieces[k].lower() if(k!=len(pieces)-1): query += pieces[k]+"+" else: query += pieces[k] url = "https://www.google.co.in/search?site=&source=hp&q=" url += query # print colored("\n"+url+"\n",'yellow') # web scraping google is forbidden, hence headers are needed as a workaround headers={'User-Agent':user_agent,} request=urllib2.Request(url,None,headers) response = urllib2.urlopen(request) # complete code is saved in "code" code = response.read() # save code file offline as "page_content.html" with open('page_content.html', 'wb') as fid: fid.write(code) # make a soup object from html code soup = BeautifulSoup(code,"html.parser") # found will be None if the specified tags are not found in code found = soup.find("div", { "class" : "_tXc" }) if(found==None): found = soup.find("table", { "style" : "font-size:14px;width:100%" }) if(found!=None): # delete the prefix noun/pronoun/verb/adjective toDelete = soup.find("div", { "style" : "color:#666;padding:5px 0" }).get_text() output = found.get_text() output = output[len(toDelete):] print colored("\n"+output+"\n",'yellow') ip.play(output) else: found = soup.find("div", { "class" : "_o0d" }) if(found!=None): output = found.get_text() # if the top result is a youtube video, play it using youtube function if(output.find("https://www.youtube.com/watch?v=")!=-1): link = output[output.find("https"):] ip.play("Playing youtube video..") print colored("\nPlaying youtube video..\n",'green') you.youtube(link,1,device) else: print colored("\n"+output+"\n",'yellow') ip.play(output) else: # no straightaway answer from google, only webpages available print colored("\nWill mail the link to you.\n",'green') ip.play("Will mail the link to you.") else: output = found.get_text() print colored("\n"+output+"\n",'yellow') ip.play(output) # remove the html code once function finishes os.system("rm page_content.html")
from youtube import youtube output=youtube('your search query') #like youtube('pink floyd high hopes')
from pathlib import Path from pytube import YouTube import os import sys from youtube import youtube youtube()
fg="white", anchor="center", command=lambda: [clearFrame(canvas), printAll(canvas, font)]) btn_remd["font"] = font btn_music = tk.Button( frame_opt, text='音樂 & Youtube', width=12, height=2, bd=0, bg="#33383E", fg="white", anchor="center", command=lambda: [clearFrame(canvas), youtube(canvas, font)]) btn_music["font"] = font btn_news = tk.Button( frame_opt, text='新聞', width=12, height=2, bd=0, bg="#33383E", fg="white", anchor="center", command=lambda: [clearFrame(canvas), refreshNews(canvas, font)]) btn_news["font"] = font #Packs