Ejemplo n.º 1
0
 def play(self):
     if self.name == "vlc":
         vlc.play()
     if self.name == "kodi":
         kodi.play()
         return
     if self.name == "mpv":
         return
Ejemplo n.º 2
0
def btn_c_action(pin, event):
    global running
    if not running:
        return

    global last_input
    global vlc

    last_input = time.time()
    if event != PushButton.PRESSED:
        return
    if exit_menu:
        reboot()
        return
    if vlc.is_playing():
        vlc.pause()
        log("pausing")
    else:
        vlc.play()
        log("playing...")
Ejemplo n.º 3
0
def assistant(command):
    "if statements for executing commands"

    #open reddit
    if "open reddit" in command:
        url = "https://www.reddit.com"
        webbrowser.open(url)
        sofiaResponse("Reddit has been opened for you Sir")

    elif "shutdown" in command:
        sofiaResponse("Bye bye. Have a nice day")
        sys.exit()

    #open a website
    elif "visit" in command:
        reg_ex = re.search("open (.+)", command)
        if reg_ex:
            domain = reg_ex.group(1)
            print(domain)
            url = "http://www." + domain
            webbrowser.open(url)
            sofiaResponse(
                "The website you requested has been open for you Sir,")
        else:
            pass

    #Greetings
    elif "hello" in command:
        day_time = int(strftime("%H"))
        if day_time < 12:
            sofiaResponse("Hello Sir. Good morning")
        elif 12 <= day_time < 18:
            sofiaResponse("Hello Sir. Good afternoon")
        else:
            sofiaResponse("Hello Sir. Good evening")

    #help
    elif "help me" in command:
        sofiaResponse("""You can use these commands and I'll help you out:
        1. Open reddit subreddit : Opens the subreddit in default browser.
        2. Open xyz.com : replace xyz with any website name
        3. Current weather in {cityname} : Tells you the current condition and temperture
        4. Hello
        5. play me a video : Plays song in your VLC media player
        6. change wallpaper : Change desktop wallpaper
        7. news for today : reads top news of today
        8. time : Current system time
        9. top stories from google news (RSS feeds)
        10. tell me about xyz : tells you about xyz
        """)

    #tell a joke
    elif "joke" in command:
        res = requests.get('https://icanhazdadjoke.com/',
                           headers={"Accept": "application/json"})
        if res.status_code == requests.codes.ok:
            sofiaResponse(str(res.json()['joke']))
        else:
            sofiaResponse("Ooops, I ran out of jokes")

    #top stories from google
    elif "news for today" in command:
        try:
            news_url = "https://news.google.com/news/rss"
            Client = urlopen(news_url)
            xml_page = Client.read()
            Client.close()
            soup_page = soup(xml_page, "xml")
            news_list = soup_page.findAll("items")
            for news in news_list[:15]:
                sofiaResponse(news.title.text.encode('utf-8'))
        except Exception as e:
            print(e)

    #current weather
    elif "current weather" in command:
        reg_ex = re.search("current weather in (.+)", command)
        if reg_ex:
            city = reg_ex.group(1)
            owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa')
            obs = owm.weather_at_place(city)
            w = obs.get_weather()
            k = w.get_status()
            x = w.get_temperature(unit="celsius")
            sofiaResponse(
                'Current weather in %s is %s. The maximum temperature is %0.2f and '
                'the minimum temperature is %0.2f degree celcius' %
                (city, k, x['temp_max'], x['temp_min']))

    #tell time
    elif "time" in command:
        import datetime
        now = datetime.datetime.now()
        sofiaResponse("Current time is %d hours %d minutes" %
                      (now.hour, now.minute))

    #send mail
    elif 'email' in command:
        sofiaResponse('Who is the recipient?')
        recipient = myCommand()
        if 'friend' in recipient:
            sofiaResponse('What should I say to him?')
            content = myCommand()
            mail = smtplib.SMTP('smtp.gmail.com', 587)
            mail.ehlo()
            mail.starttls()
            mail.login('your_email_address', 'your_password')
            mail.sendmail('sender_email', 'receiver_email', content)
            mail.close()
            sofiaResponse(
                'Email has been sent successfuly. You can check your inbox.')
        else:
            sofiaResponse('I don\'t know what you mean!')

    #launch any app
    elif "open" in command:
        reg_ex = re.search("launch (.+)", command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname + ".exe"
            subprocess.Popen(["open", "-n", "/Applications/" + appname1],
                             stdout=subprocess.PIPE)
        sofiaResponse("I have launched the desired app")

    # play youtube song
    elif "play me a song" in command:
        path = '//Users/Sir_Lighton/video'
        folder = path
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
        try:
            if os.path.isfile(file_path):
                os.unlink(file_path)
        except Exception as e:
            print(e)
    sofiaResponse('What song shall I play Sir?')
    mysong = myCommand()
    if mysong:
        flag = 0
        url = "https://www.youtube.com/results?search_query=" + mysong.replace(
            ' ', '+')
        response = urllib.request.urlopen(url)
        html = response.read()
        soup1 = soup(html, "lxml")
        url_list = []
        for vid in soup1.findAll(attrs={'class': 'yt-uix-tile-link'}):
            if ('https://www.youtube.com' + vid['href']
                ).startswith("https://www.youtube.com/watch?v="):
                flag = 1
                final_url = 'https://www.youtube.com' + vid['href']
                url_list.append(final_url)
        url = url_list[0]
        ydl_opts = {}
        os.chdir(path)
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download([url])
            vlc.play(path)
            if flag == 0:
                sofiaResponse('I have not found anything in Youtube ')


#askme anything
    elif 'tell me about' in command:
        reg_ex = re.search('tell me about (.*)', command)
        try:
            if reg_ex:
                topic = reg_ex.group(1)
                ny = wikipedia.page(topic)
                sofiaResponse(ny.content[:500].encode('utf-8'))
        except Exception as e:
            print(e)
            sofiaResponse(e)
Ejemplo n.º 4
0
def assistant(command):
    "if statements for executing commands"

    #open subreddit Reddit
    if 'open reddit' in command:
        reg_ex = re.search('open reddit (.*)', command)
        url = 'https://www.reddit.com/'
        if reg_ex:
            subreddit = reg_ex.group(1)
            url = url + 'r/' + subreddit
        webbrowser.open(url)
        sofiaResponse('The Reddit content has been opened for you Sir.')

    elif 'shutdown' in command:
        sofiaResponse('Bye bye Sir. Have a nice day')
        sys.exit()

    #open website
    elif 'open' in command:
        reg_ex = re.search('open (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            print(domain)
            url = 'https://www.' + domain
            webbrowser.open(url)
            sofiaResponse('The website you have requested has been opened for you Sir.')
        else:
            pass

    #greetings
    elif 'hello' in command:
        day_time = int(strftime('%H'))
        if day_time < 12:
            sofiaResponse('Hello Sir. Good morning')
        elif 12 <= day_time < 18:
            sofiaResponse('Hello Sir. Good afternoon')
        else:
            sofiaResponse('Hello Sir. Good evening')

    elif 'help me' in command:
        sofiaResponse("""
        You can use these commands and I'll help you out:

        1. Open reddit subreddit : Opens the subreddit in default browser.
        2. Open xyz.com : replace xyz with any website name
        3. Send email/email : Follow up questions such as recipient name, content will be asked in order.
        4. Tell a joke/another joke : Says a random dad joke.
        5. Current weather in {cityname} : Tells you the current condition and temperture
        7. Greetings
        8. play me a video : Plays song in your VLC media player
        9. change wallpaper : Change desktop wallpaper
        10. news for today : reads top news of today
        11. time : Current system time
        12. top stories from google news (RSS feeds)
        13. tell me about xyz : tells you about xyz
        """)


    #top stories from google news
    elif 'news for today' in command:
        try:
            news_url="https://news.google.com/news/rss"
            Client=urlopen(news_url)
            xml_page=Client.read()
            Client.close()
            soup_page=soup(xml_page,"xml")
            news_list=soup_page.findAll("item")
            for news in news_list[:15]:
                sofiaResponse(news.title.text.encode('utf-8'))
        except Exception as e:
                print(e)

    #current weather
    elif 'current weather' in command:
        reg_ex = re.search('current weather in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            owm = OWM(API_key='*****************')
            obs = owm.weather_at_place(city)
            w = obs.get_weather()
            k = w.get_status()
            x = w.get_temperature(unit='celsius')
            sofiaResponse('Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius' % (city, k, x['temp_max'], x['temp_min']))

    #time
    elif 'time' in command:
        import datetime
        now = datetime.datetime.now()
        sofiaResponse('Current time is %d hours %d minutes' % (now.hour, now.minute))

    #send email
    elif 'email' in command:
        sofiaResponse('Who is the recipient?')
        recipient = myCommand()
        if 'david' in recipient:
            sofiaResponse('What should I say to him?')
            content = myCommand()
            mail = smtplib.SMTP('smtp.gmail.com', 587)
            mail.ehlo()
            mail.starttls()
            mail.login('*****@*****.**', '*************')
            mail.sendmail('*****@*****.**', '*****@*****.**', content)
            mail.close()
            sofiaResponse('Email has been sent successfuly. You can check your inbox.')
        else:
            sofiaResponse('I don\'t know what you mean!')

    #launch any application
    elif 'launch' in command:
        reg_ex = re.search('launch (.*)', command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname+".app"
            subprocess.Popen(["open", "-n", "/Applications/" + appname1], stdout=subprocess.PIPE)

        sofiaResponse('I have launched the desired application')

    #play youtube song
    elif 'play me a song' in command:
        path = '/Users/nageshsinghchauhan/Documents/videos/'
        folder = path
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)

        sofiaResponse('What song shall I play Sir?')
        mysong = myCommand()
        if mysong:
            flag = 0
            url = "https://www.youtube.com/results?search_query=" + mysong.replace(' ', '+')
            response = urllib2.urlopen(url)
            html = response.read()
            soup1 = soup(html,"lxml")
            url_list = []
            for vid in soup1.findAll(attrs={'class':'yt-uix-tile-link'}):
                if ('https://www.youtube.com' + vid['href']).startswith("https://www.youtube.com/watch?v="):
                    flag = 1
                    final_url = 'https://www.youtube.com' + vid['href']
                    url_list.append(final_url)

            url = url_list[0]
            ydl_opts = {}

            os.chdir(path)
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([url])
            vlc.play(path)

            if flag == 0:
                sofiaResponse('I have not found anything in Youtube ')

    #change wallpaper
    elif 'change wallpaper' in command:
        folder = '/Users/nageshsinghchauhan/Documents/wallpaper/'
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
        api_key = '***************'
        url = 'https://api.unsplash.com/photos/random?client_id=' + api_key #pic from unspalsh.com
        f = urllib2.urlopen(url)
        json_string = f.read()
        f.close()
        parsed_json = json.loads(json_string)
        photo = parsed_json['urls']['full']
        urllib.urlretrieve(photo, "/Users/nageshsinghchauhan/Documents/wallpaper/a") # Location where we download the image to.
        subprocess.call(["killall Dock"], shell=True)
        sofiaResponse('wallpaper changed successfully')

    #ask me anything
    elif 'tell me about' in command:
        reg_ex = re.search('tell me about (.*)', command)
        try:
            if reg_ex:
                topic = reg_ex.group(1)
                ny = wikipedia.page(topic)
                sofiaResponse(ny.content[:500].encode('utf-8'))
        except Exception as e:
                print(e)
                sofiaResponse(e)
Ejemplo n.º 5
0
def assistant(command):
    if 'open reddit' in command:
        reg_ex = re.search('open reddit (.*)', command)
        url = 'https://www.reddit.com/'
        if reg_ex:
            subreddit = reg_ex.group(1)
            url = url + 'r/' + subreddit
        webbrowser.open(url)
        martinResponse('The Reddit content has been opened for you Sir.')

    elif 'open' in command:
        reg_ex = re.search('open (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            print(domain)
            url = 'https://www.' + domain
            webbrowser.open(url)
            martinResponse(
                'The website you have requested has been opened for you Sir.')
        else:
            pass

    elif 'email' in command:
        martinResponse('Who is the recipient?')
        recipent = myCommand()

        if 'rajat' in recipent:
            martinResponse('What should I say to him?')
            content = myCommand()
            mail = smtplib.SMTP('smtp.gmail.com', 587)
            mail.ehlo()
            mail.starttls()
            mail.login('your_email_address', 'your_password')
            mail.sendmail('sender_email', 'receiver_email', content)
            mail.close()
            martinResponse(
                'Email has been sent successfuly. You can check your inbox.')

        else:
            martinResponse('I don\'t know what you mean!')
    # opens applications for me
    elif 'launch' in command:
        reg_ex = re.search('launch (.*', command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname + ".app"
            subprocess.Popen(["open", "-n", "/Applications/" + appname1],
                             stdout=subprocess.PIPE)
            martinResponse('I have launched the desired appication')
    # the weather sis
    elif 'current  weather' in command:
        reg_ex = re.search('current weather in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            owm = OWM(API_key='ab0d5e80e8dafb2cb91fa9e82431c1fa')
            obs = owm.weather_at_place(city)
            w = obs.get_weather()
            k = w.get_status()
            x = w.get_temperature(unit='celsius')
            martinResponse(
                'Current weather in %s is %s. The maximum temperature is %0.3f and the minumum temperature is %0.3f degree celsius'
                % (city, k, x['temp_max'], x['temp_min']))
    # time bro
    elif 'time' in command:
        import datetime
        now = datetime.datetime.now()
        martinResponse('Current time is %d hours %d minutes' %
                       (now.hour, now.minute))

    # Greet martin
    elif 'hello' in command:
        day_time = int(strftime('%H'))
        if day_time < 12:
            martinResponse('Hello Sir. Good morning')
        elif 12 <= day_time < 18:
            martinResponse('Hello Sir. Good afternoon')
        else:
            martinResponse('Hello Sir. Good evening')

    # to terminate the program
    elif 'shutdown' in command:
        martinResponse('Bye bye Sir. Have a nice day')
        sys.exit()

    # play me a song

    elif 'play me a song' in command:
        path = '/Users/user/Movies/'
        folder = path
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)

        martinResponse('What song shall I play Sir?')
        mysong = myCommand()
        if mysong:
            flag = 0
            url = "https://www.youtube.com/results?search_query" + mysong.replace(
                ' ', '+')
            response = urllib.urlopen(url)
            html = response.read()
            soup1 = soup(html, "lxml")
            url_list = []
            for vid in soup1.findAll(attrs={'class': 'yt-uix-tile-link'}):
                if ('https://www.youtube.com' + vid['href']
                    ).startswith("https://www.youtube.com/watch?v="):
                    flag = 1
                    final_url = 'https://www.youtube.com' + vid['href']
                    url_list.append(final_url)
                    url = url_list[0]
                    ydl_opts = {}
                    os.chdir(path)
                    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                        ydl.download([url])
                    vlc.play(path)

        if flag == 0:
            martinResponse('I have not found anything in Youtube')
    #martin changes my wallpaper

    elif 'change wallpaper' in command:
        folder = '/User/user/Documents/walllpaper'
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
            API_key = 'fd66364c0ad9e0f8aabe54ec3cfbed0a947f3f4014ce3b841bf2ff6e20948795'
            url = 'https://api.unsplash.com/photos/random?client_id=' + API_key
            f = urllib.urlopen(url)
            json_string = f.read()
            f.close()
            parsed_json = json.loads(json_string)
            photo = parsed_json['urls']['full']
            urllib.urlretrieve(photo, "/Users/user/Documents/wallpaper/")
            subprocess.call(["killall Dock"], shell=True)
            martinResponse('wallpaper changed successfully')

    #news
    elif 'news for today' in command:
        try:
            news_url = "https://news.google.com/news/rss"
            Client = urlopen(news_url)
            xml_page = Client.read()
            Client.close()
            soup_page = soup(xml_page, "xml")
            news_list = soup_page.findAll("item")
            for news in news_list[:15]:
                martinResponse(news.title.text.encode('utf-8'))
        except Exception as e:
            print(e)
    #about anything
    elif 'tell me about' in command:
        reg_ex = re.search('tell me about (.*)', command)
        try:
            if reg_ex:
                topic = reg_ex.group(1)
                ny = wikipedia.page(topic)
                martinResponse(ny.content[:500].encode('utf=8'))
        except Exception as e:
            martinResponse(e)
Ejemplo n.º 6
0
def play():
    vlc.play()
    return redirect(_referrer())
Ejemplo n.º 7
0
def assistant(command):
    "if statements for executing commands"
    #open_subreddit_Reddit function
    if 'open reddit' in command:
        reg_ex = re.search('open reddit (.*)', command)
        url = 'https://www.reddit.com/'
        if reg_ex:
            subreddit = reg_ex.group(1)
            url = url + 'r/' + subreddit
        webbrowser.open(url)
        IvyResponse('Yo, it is the subreddit you were asking for.')
    elif 'shutdown' in command:
        IvyResponse(
            "See you later. You know where to wake me. Have a nice day")
        sys.exit()
#open_specific_website function
    elif 'open' in command:
        reg_ex = re.search('open (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            print(domain)
            url = 'https://www.' + domain
            webbrowser.open(url)
            IvyResponse('The website you needed has been opened for you mate.')
        else:
            pass
#greetings function
    elif 'hello' in command:
        day_time = int(strftime('%H'))
        if day_time < 12:
            IvyResponse("Hey,Good morning")
        elif 12 <= day_time < 18:
            IvyResponse("Hello, Good afternoon")
        else:
            IvyResponse("It is the evening at the moment, How can I help you?")
    elif 'help me' in command:
        IvyResponse("""
        You can use one of those function and I will help you out:
        1. Open reddit subreddit : I will open the subreddit in default browser
        2. Open xyz.com: Please replace xyz with any website name and I will open it for ya.
        3. Send email: Follow up questions such as recipient name, content will be asked in order.
        4. Current weather in {cityname}: I will tell you the current weather status in a specific place
        5. Hello : You know what is this for right?
        6. Play me a video: I will play song in your VLC media player (please install it in advance)
        7. Change wallpaper : Changing destop wallpaper (of course it is randomed)
        8. News for today: It is news from the media for you mate. No need to thank me
        9. Time: Displaying current system time
        10.RRS feeds: Top stroies from google news just for ya
        11.Tell me about xyz: Replace xyz with what you wanna know, I got the whole wiki and google library so give me your best shot!!
        """)
#joke function
    elif 'joke' in command:
        res = requests.get('https://icanhazdadjoke.com/',
                           headers={"Accept": "application/json"})
        if res.status_code == requests.codes.ok:
            IvyResponse(str(res.json()['joke']))
        else:
            IvyResponse(
                'Oops! Wanna hear someting horrible! I ran out of joke')
#top_stories_from_google_news function
    elif 'news for today' in command:
        try:
            news_url = "https://news.google.com/news/rss"
            Client = urlopen(news_url)
            xml_page = Client.read()
            Client.close()
            soup_page = soup(xml_page, "xml")
            news_list = soup_page.findALL("item")
            for news in news_list[:15]:
                IvyResponse(news.title.text.encode('utf-8'))
        except Exception as e:
            print(e)
#Current_weather function
    elif 'current weather' in command:
        reg_ex = re.search('current weather in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa')
            obs = owm.weather_at_place(city)
            w = obs.get_weather()
            k = w.get_status()
            x = w.get_temperature(unit='celsius')
            IvyResponse(
                'Current Weather right now in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius'
                % (city, k, x['temp_max'], x['temp_min']))
#time function
    elif 'time' in command:
        import datetime
        now = datetime.datetime.now()
        IvyResponse('Current time is %d hours %d minutes' %
                    (now.hour, now.minute))
    elif 'email' in command:
        IvyResponse('Who is the recipient?')
        recipient = myCommand()
        if "mailey" in recipient:
            IvyResponse('What should I send to her')
            content = myCommand()
            mail = smtplib.SMTP('smtp.gmail.com', 587)
            mail.ehlo()
            mail.startls()
            mail.logic('your_email_address', 'your_password')
            mail.sendmail('sender_email', 'receiver_email', content)
            mail.close()
            IvyResponse(
                'The email has been sent. You can check your inbox though.')
        else:
            IvyResponse('I don\'t know what you mean!')
#launch_any_application function
    elif 'launch' in command:
        reg_ex = re.search('launch(.*)', command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname + ".app"
            subprocess.Popen(["open", "-n", "/Applications/" + appname1],
                             stdout=subprocess.PIPE)
        IvyResponse(
            "I have launch the application as you wanted, No thanks needed!")

#play_youtube_songs function
    elif 'play me a song' in command:
        path = '/Users/vuquoccuong121994/Documents/videos'
        folder = path
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
        IvyResponse('What song you want me to play')
        mysong = myCommand()
        if mysong:
            flag = 0
            url = "https://www.youtube.com/results?search_query=" + mysong.replace(
                ' ', '+')
            response = urllib.request.urlopen(url)
            html = response.read()
            soup1 = soup(html, 'lxml')
            url_list = []
            for vid in soup1.findAll(attrs={'class': 'yt-uix-tile-link'}):
                if ('http://www.youtube.com' + vid['href']
                    ).startswith('https://www.youtube.com/watch?v='):
                    flag = 1
                    final_url = 'https://www.youtube.com' + vid['href']
                    url.list.append(final_url)
        url = url_list[0]
        ydl_opts = {}
        os.chdir(path)
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download([url])
            vlc.play(path)
        if flag == 0:
            IvyResponse(
                'Oops! Nothing on Youtube to be found as you requested')
#change_wallpaper function
    elif 'change wallpaper' in command:
        folder = '/Users/vuquoccuong121994/Documents/wallpaper/'
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
        api_key = 'fd66364c0ad9e0f8aabe54ec3cfbed0a947f3f4014ce3b841bf2ff6e20948795'
        url = 'https://api.unsplash.com/photos/random?client_id=' + api_key  #this will take content from unsplash.com
        f = urllib.request.urlopen(url)
        json_string = f.read()
        f.close()
        parsed_json = json.loads(json.string)
        photo = parsed_json['urls']['full']
        urllib.request.urlretrieve(
            photo, "/Users/vuquoccuong121994/Documents/wallpaper/a"
        )  #this will be the location for image to be downloaded
        subprocess.call(["killall Dock"], shell=True)
        IvyResponse('Wallpaper has been successfully changed')
#ask_me_anything function
    elif 'tell me about' in command:
        reg_ex = re.search('tell me about (.*)', command)
        try:
            if reg_ex:
                topic = reg_ex.group(1)
                ny = wikipedia.page(topic)
                IvyResponse(ny.content[:500].encode('utf-8'))
        except Exception as e:
            print(e)
            IvyResponse(e)
        IvyResponse(
            'Hi there, I am Ivy and I am your personal Voice assistant! I am here to help you with your daily tasks so you can be more focused on your life\'s purpose. Please ask me anything or say "Help me" and I will tell you what all I can do for ya.'
        )
#loop to continue executing multiple commands
    while True:
        assistant(myCommand())
Ejemplo n.º 8
0
def assistant(command):
    "Some rule based learning"
    greetings = ['hey there', 'hello', 'hi', 'hai', 'hey', 'hey']
    question = ['how are you', 'how are you doing']
    responses = [
        'Okay', "I am fine, Thanks for asking", "I am pretty good",
        "Not too shabby", "Very well,Thank you", "Happy as a clamShell Mac",
        " I feel good", "I am Happy as a happy mac",
        "I am happy as finder, Actually no...no Noone can be happy as finder",
        "If i were any better, vitamins would be taking me"
    ]
    creation = [
        'who made you', 'who created you', 'who build you', 'who invented you'
    ]
    creation_reply = [
        'I was created by Suryakant right in his Mac', 'Suryakant',
        'Some guy whom i never got to know',
        'I, alianna, designed by Suryakant in his Mac'
    ]
    intro = [
        "who are you", "what is your name", "introduce", "introduce yourself"
    ]
    intro_reply = [
        " I am alianna, here to help", "Who I am is not important",
        "I am alianna", "My name, its alianna",
        "i am alianna, but i do not like talking about myself", "alianna",
        "i am just a humble virtual assistant",
        "My name is alianna, but you knew that already",
        "alianna, pleased to meet you"
    ]
    google = [
        'open browser', 'open google', "google", "let me google",
        "open chrome", "open any browser", "open default browser",
        "open google for me"
    ]
    song = [
        'song', 'play some music', 'play music', 'play songs', 'play a song',
        'open music player', 'alianna play some music', 'open itunes',
        'sing a song', 'song please'
    ]
    video = [
        'open youtube', 'i want to watch a video', 'i want to watch video',
        'i want to watch some videos', 'i am feeling boring'
    ]
    close = [
        'exit', 'close', 'goodbye', 'nothing', 'shut down',
        "go alianna take some rest", "alianna take some rest", "bye",
        "bye alianna"
    ]
    color = [
        'what is your color', 'what is your colour', 'your color',
        'what color you wear', 'what color you are wearing',
        'what color you made of'
    ]
    color_reply = [
        'Right now its rainbow', "Hey what's with all that personal questions",
        'Right now its transparent',
        'It depends on the lighting, and on my mood',
        'the color of omniscience'
    ]
    fav_color = [
        'what is your favourite colour', 'your favourite color',
        'favourite color', 'what color do you like'
    ]
    compliment = [
        'thank you', 'thankyou', 'thanks', 'thanks a lot', 'thanks buddy',
        'thanks alianna', 'thanks a lot alianna', 'thank you alianna'
    ]
    compliment_reply = [
        'youre welcome', 'glad i could help you', 'Sure thing',
        'dont mention it', 'no problem', 'no worries', 'my pleasure'
    ]

    # open reddit (Give command like this: open reddit for me)
    if 'open reddit' in command:
        reg_ex = re.search('open reddit (.*)', command)
        url = 'https://www.reddit.com/'
        if reg_ex:
            subreddit = reg_ex.group(1)
            url = url + 'r/' + subreddit
        webbrowser.open(url)
        aliannaResponse('The Reddit content has been opened for you Sir.')

    # open google (Give command like this: open google for me)
    elif command in google:
        webbrowser.open('https://www.google.com/')
        aliannaResponse('The browser has been opened for you Sir.')

    # open youtube (Give any command from list named "video")
    elif command in video:
        reply = random.choice(video)
        webbrowser.open('https://www.youtube.com/')
        aliannaResponse(
            'I think youtube is a good platform to watch. Enjoy your song sir')

    # open any website (Give command like this: open facebook.com)
    elif 'open' in command:
        reg_ex = re.search('open (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            print(domain)
            url = 'https://www.' + domain
            webbrowser.open(url)
            aliannaResponse(
                'The website you have requested has been opened for you Sir.')
        else:
            pass

    # greetings (Greet in any ways from list named "greeting")
    elif command in greetings:
        day_time = int(strftime('%H'))
        if day_time < 12:
            aliannaResponse('Hello Sir. Good morning. What can i do for you?')
        elif 12 <= day_time < 18:
            aliannaResponse(
                'Hello Sir. Good afternoon. What can i do for you?')
        else:
            aliannaResponse('Hello Sir. Good evening. What can i do for you?')

    # Tasks (It will tell, what tasks it can perfrom)
    elif 'help me' in command:
        aliannaResponse(
            "I am allowed to do some sort of work like: Open reddit subreddit, Open any website, Send email, Current weather in any city, Greetings, play any video, change wallpaper, news for today, Current time, top stories from google news, or anything limited to my knowledge"
        )

    # joke (Give command like this: tell me some joke)
    elif 'joke' in command:
        res = requests.get('https://icanhazdadjoke.com/',
                           headers={"Accept": "application/json"})
        if res.status_code == requests.codes.ok:
            aliannaResponse(str(res.json()['joke']))
        else:
            aliannaResponse('oops!I ran out of jokes')

    # top stories from google news (Give command like this: Tell me news for today)
    elif 'news for today' in command:
        try:
            news_url = "https://news.google.com/news/rss"
            Client = urlopen(news_url)
            xml_page = Client.read()
            Client.close()
            soup_page = soup(xml_page, "xml")
            news_list = soup_page.findAll("item")
            for news in news_list[:5]:
                aliannaResponse(news.title.text)
        except Exception as e:
            print(e)

    # current weather (Give command like this: Current weather in London or pinCode)
    elif 'current weather' in command:
        reg_ex = re.search('current weather in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            owm = OWM(API_key='1ad8a325429ff07a9229415c22ffa76b')
            obs = owm.weather_at_place(city)
            w = obs.get_weather()
            h = w.get_humidity()
            k = w.get_detailed_status()
            x = w.get_temperature(unit='celsius')
            aliannaResponse(
                'Current weather in %s is %s, The current temperature is %0.1f degeree celcius, maximum temperature is %0.1f, and the minimum temperature is %0.1f degree celcius, climate contains %0.1f percent humidity'
                % (city, k, x['temp'], x['temp_max'], x['temp_min'], h))

    # time (Give command like this: what is current time?)
    elif 'time' in command:
        now = datetime.datetime.now()
        aliannaResponse('Current time is %d hours %d minutes' %
                        (now.hour, now.minute))

    # email (Give command like this: Send an email for me)
    elif 'email' in command:
        sender_email = '*****@*****.**'
        sender_email_password = '******'
        receiver_email = '*****@*****.**'
        aliannaResponse('Who is the recipient?')
        recipient = myCommand()
        if 'suryakant' in recipient:
            aliannaResponse('What should I say to him?')
            content = myCommand()
            mail = smtplib.SMTP('smtp.gmail.com', 587)
            mail.ehlo()
            mail.starttls()
            mail.login(sender_email, sender_email_password)
            mail.sendmail(sender_email, receiver_email, content)
            mail.close()
            aliannaResponse(
                'Email has been sent successfuly. You can check your inbox.')
        else:
            aliannaResponse('I don\'t know what you mean!')

    # launch any application on the system/MacOS (Give command like this: Launch itunes)
    elif 'launch' in command:
        reg_ex = re.search('launch (.*)', command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname + ".app"
            subprocess.Popen(["open", "-n", "/Applications/" + appname1],
                             stdout=subprocess.PIPE)
            aliannaResponse('I have launched the desired application')

    # play youtube song (Give command like this: Play me a song)
    elif 'play me a song' in command:
        path = '/Users/suryakantkumar/aliannaAssistant/downloads/'
        folder = path
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
        aliannaResponse('What song shall I play Sir?')
        mysong = myCommand()
        if mysong:
            flag = 0
            url = "https://www.youtube.com/results?search_query=" + mysong.replace(
                ' ', '+')
            response = urlopen(url)
            html = response.read()
            soup1 = soup(html, "lxml")
            url_list = []
            for vid in soup1.findAll(attrs={'class': 'yt-uix-tile-link'}):
                if ('https://www.youtube.com' + vid['href']
                    ).startswith("https://www.youtube.com/watch?v="):
                    flag = 1
                    final_url = 'https://www.youtube.com' + vid['href']
                    url_list.append(final_url)
            url = url_list[0]
            ydl_opts = {}
            os.chdir(path)
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([url])
            vlc.play(path)
            if flag == 0:
                aliannaResponse('I have not found anything in Youtube ')

    # changes wallpaper from splash (Give command like this: Change wallpaper)
    elif 'change wallpaper' in command:
        folder = '/Users/suryakantkumar/aliannaAssistant/wallpaper/'
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
        api_key = '1ab94638c94b887262e5a4d180c078f12929c6bea5c3e420e4a7eee7b41fb7d'
        url = 'https://api.unsplash.com/photos/random?client_id=' + api_key  # pic from unspalsh.com
        f = urlopen(url)
        json_string = f.read()
        f.close()
        parsed_json = json.loads(json_string)
        photo = parsed_json['urls']['full']
        # Location where we download the image to.
        urllib.request.urlretrieve(
            photo, '/Users/suryakantkumar/aliannaAssistant/wallpaper/a.jpg')
        subprocess.call(["killall Dock"], shell=True)
        aliannaResponse('wallpaper changed successfully')

    # askme anything (Give command like this: Tell me about Elon musk)
    elif 'tell me about' in command:
        reg_ex = re.search('tell me about (.*)', command)
        try:
            if reg_ex:
                topic = reg_ex.group(1)
                wiki = wikipedia.page(topic)
                aliannaResponse(wiki.content[:500])
        except Exception as e:
            print(e)
            aliannaResponse(e)

    # Ask about (Give any command from list named "question")
    elif command in question:
        reply = random.choice(responses)
        aliannaResponse(reply)

    # Ask about creation of it (Give any command from list named "creation")
    elif command in creation:
        reply = random.choice(creation_reply)
        aliannaResponse(reply)

    # Compliment (Give any command from list named "compliment")
    elif command in compliment:
        reply = random.choice(compliment_reply)
        aliannaResponse(reply)

    # Listen songs from iTunes (Give any command from list named "song")
    elif command in song:
        appname = 'iTunes.app'
        subprocess.Popen(["open", "-n", "/Applications/" + appname],
                         stdout=subprocess.PIPE)

    # Assistant's color (Give any command from list named "color")
    elif command in color:
        reply = random.choice(color_reply)
        aliannaResponse(reply)
        # aliannaResponse('It keeps changing every micro second')

    # Favourite color (Give any command from list named "fav_color")
    elif command in fav_color:
        reply = random.choice(color_reply)
        aliannaResponse(reply)

    # Introduction (Give any command from list named "intro")
    elif command in intro:
        reply = random.choice(intro_reply)
        aliannaResponse(reply)

    # Shut Down (Give any command from list named "close")
    elif command in close:
        aliannaResponse('Bye bye Sir. See you later.')
        sys.exit()
Ejemplo n.º 9
0
def _cli(path=None):
    vlc.play(path)
Ejemplo n.º 10
0
            url = "https://www.youtube.com/results?search_query=" + mysong.replace(' ', '+')
            response = urllib2.urlopen(url)
            html = response.read()
            soup1 = soup(html,"lxml")
            url_list = []
            for vid in soup1.findAll(attrs={'class':'yt-uix-tile-link'}):
                if ('https://www.youtube.com' + vid['href']).startswith("https://www.youtube.com/watch?v="):
                    flag = 1
                    final_url = 'https://www.youtube.com' + vid['href']
                    url_list.append(final_url)
url = url_list[0]
            ydl_opts = {}
os.chdir(path)
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([url])
            vlc.play(path)
if flag == 0:
                sofiaResponse('I have not found anything in Youtube ')
#change wallpaper
    elif 'change wallpaper' in command:
        folder = '/Users/nageshsinghchauhan/Documents/wallpaper/'
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
        api_key = 'fd66364c0ad9e0f8aabe54ec3cfbed0a947f3f4014ce3b841bf2ff6e20948795'
        url = 'https://api.unsplash.com/photos/random?client_id=' + api_key #pic from unspalsh.com
        f = urllib2.urlopen(url)
Ejemplo n.º 11
0
def assistant(command):
    "if statements for executing commands"

    #open subreddit Reddit
    if command in greetings:
        sofiaResponse1(
            'Hi User, I am Sofia and I am your personal voice assistant, Please give a command or say "help me" and I will tell you what all I can do for you.'
        )

        #chatbot
    elif command in question:
        sofiaResponse1('I am fine')
        print('I am fine')
    elif command in var1:
        sofiaResponse1('I was made by sudeesh')
        reply = random.choice(var2)
        print(reply)
    elif command in cmd9:
        print(random.choice(repfr9))
        sofiaResponse1(random.choice(repfr9))
    elif command in cmd7:
        print(random.choice(colrep))
        sofiaResponse1(random.choice(colrep))
        print('It keeps changing every micro second')
        sofiaResponse1('It keeps changing every micro second')
    elif command in cmd8:
        print(random.choice(colrep))
        sofiaResponse1(random.choice(colrep))
        print('It keeps changing every micro second')
        sofiaResponse1('It keeps changing every micro second')
    elif command in cmd2:
        mixer.init()
        mixer.music.load("song.wav")
        mixer.music.play()
    elif command in var4:
        sofiaResponse1('I am a bot, silly')
    elif command in cmd4:
        webbrowser.open('www.youtube.com')
    elif command in cmd6:
        print('see you later')
        sofiaResponse1('see you later')
    elif command in var3:
        print("Current date and time : ")
        print(now.strftime("The time is %H:%M"))
        sofiaResponse1(now.strftime("The time is %H:%M"))
    elif command in cmd1:
        webbrowser.open('www.google.com')
    elif command in cmd3:
        jokrep = random.choice(jokes)
        sofiaResponse1(jokrep)

    elif 'open reddit' in command:
        reg_ex = re.search('open reddit (.*)', command)
        url = 'https://www.reddit.com/'
        if reg_ex:
            subreddit = reg_ex.group(1)
            url = url + 'r/' + subreddit
        webbrowser.open(url)
        sofiaResponse1('The Reddit content has been opened for you Sir.')
    elif 'close' in command:
        sofiaResponse1('Bye bye Sir. Have a nice day')
        script = open("assistantwelcome.py", 'r').read()
        exec(script)
        #os.system('python3 /home/pi/Desktop/chatbot')
        sys.exit()

    #open website
    elif 'open' in command:
        reg_ex = re.search('open (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            print(domain)
            url = 'https://www.' + domain
            webbrowser.open(url)
            sofiaResponse1(
                'The website you have requested has been opened for you Sir.')
        else:
            pass

    #greetings
    elif 'hello' in command:
        day_time = int(strftime('%H'))
        if day_time < 12:
            sofiaResponse1('Hello Sir. Good morning')
        elif 12 <= day_time < 18:
            sofiaResponse1('Hello Sir. Good afternoon')
        else:
            sofiaResponse1('Hello Sir. Good evening')
    elif 'help me' in command:
        print("""
            You can use these commands and I'll help you out:
    1. Open reddit subreddit : Opens the subreddit in default browser.
            2. Open xyz.com : replace xyz with any website name
            3. Send email/email : Follow up questions such as recipient name, content will be asked in order.
            4. Current weather in {cityname} : Tells you the current condition and temperture
            5. Hello
            6. play me a video : Plays song in your VLC media player
            7. change wallpaper : Change desktop wallpaper
            8. news for today : reads top news of today
            9. time : Current system time
            10. top stories from google news (RSS feeds)
            11. tell me about xyz : tells you about xyz
            """)
    #joke
    elif 'joke' in command:
        res = requests.get('https://icanhazdadjoke.com/',
                           headers={"Accept": "application/json"})
        if res.status_code == requests.codes.ok:
            sofiaResponse1(str(res.json()['joke']))
        else:
            sofiaResponse1('oops!I ran out of jokes')
    #top stories from google news
    elif 'news for today' in command:
        try:
            news_url = "https://news.google.com/news/rss"
            Client = urlopen(news_url)
            xml_page = Client.read()
            Client.close()
            soup_page = soup(xml_page, "xml")
            news_list = soup_page.findAll("item")
            for news in news_list[:15]:
                sofiaResponse1(news.title.text)
        except Exception as e:
            print(e)
    #current weather
    elif 'current weather' in command:
        reg_ex = re.search('current weather in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa')
            obs = owm.weather_at_place(city)
            w = obs.get_weather()
            k = w.get_status()
            x = w.get_temperature(unit='celsius')
            sofiaResponse1(
                'Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius'
                % (city, k, x['temp_max'], x['temp_min']))
    #time
    elif 'time' in command:
        import datetime
        now = datetime.datetime.now()
        sofiaResponse1('Current time is %d hours %d minutes' %
                       (now.hour, now.minute))
    elif 'email' in command:
        sofiaResponse1('Who is the recipient?')
        recipient = myCommand()
        if 'rajat' in recipient:
            sofiaResponse1('What should I say to him?')
            content = myCommand()
            mail = smtplib.SMTP('smtp.gmail.com', 587)
            mail.ehlo()
            mail.starttls()
            mail.login('*****@*****.**', 'sudeesh@1')
            mail.sendmail('sender_email', 'receiver_email', content)
            mail.close()
            sofiaResponse1(
                'Email has been sent successfuly. You can check your inbox.')
        else:
            sofiaResponse1('I don\'t know what you mean!')
    #launch any application
    elif 'launch' in command:
        reg_ex = re.search('launch (.*)', command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname + ".app"
            subprocess.Popen(["open", "-n", "/Applications/" + appname1],
                             stdout=subprocess.PIPE)
            sofiaResponse1('I have launched the desired application')
    #play youtube song
    elif 'play me a song' in command:
        path = '/home/sudeesh/Videos/videos'
        folder = path
        print("folder:" + folder)
        for the_file in os.listdir(folder):
            print("The file:" + the_file)
            file_path = os.path.join(folder, the_file)
            print("The file path:")
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
        sofiaResponse1('What song shall I play Sir?')
        mysong = myCommand()
        if mysong:
            flag = 0
            url = "https://www.youtube.com/results?search_query=" + mysong.replace(
                ' ', '+')
            response = urllib.request.urlopen(url)
            html = response.read()
            soup1 = soup(html, "lxml")
            url_list = []
            for vid in soup1.findAll(attrs={'class': 'yt-uix-tile-link'}):
                if ('https://www.youtube.com' + vid['href']
                    ).startswith("https://www.youtube.com/watch?v="):
                    flag = 1
                    final_url = 'https://www.youtube.com' + vid['href']
                    url_list.append(final_url)
                    url = url_list[0]
                ydl_opts = {}
                os.chdir(path)
                with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                    ydl.download([url])
                    vlc.play(path)
                if flag == 0:
                    sofiaResponse1('I have not found anything in Youtube ')
    #change wallpaper
    elif 'change wallpaper' in command:
        folder = '/Users/nageshsinghchauhan/Documents/wallpaper/'
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
        api_key = 'fd66364c0ad9e0f8aabe54ec3cfbed0a947f3f4014ce3b841bf2ff6e20948795'
        url = 'https://api.unsplash.com/photos/random?client_id=' + api_key  #pic from unspalsh.com
        f = urllib2.urlopen(url)
        json_string = f.read()
        f.close()
        parsed_json = json.loads(json_string)
        photo = parsed_json['urls']['full']
        urllib.urlretrieve(photo,
                           "/Users/nageshsinghchauhan/Documents/wallpaper/a"
                           )  # Location where we download the image to.
        subprocess.call(["killall Dock"], shell=True)
        sofiaResponse1('wallpaper changed successfully')
    elif 'search' in command:
        #options = webdriver.ChromeOptions()
        #driver = webdriver.Chrome(chrome_options=options)
        chromedriver = "/home/sudeesh/Downloads/chromedriver/chromedriver"
        os.environ["webdriver.chrome.driver"] = chromedriver
        driver = webdriver.Chrome(chromedriver)
        driver.get("https://www.google.com/search?q=" + ''.join(command))
    #askme anything
    elif 'tell me about' in command:
        reg_ex = re.search('tell me about (.*)', command)
        try:
            if reg_ex:
                topic = reg_ex.group(1)
                ny = wikipedia.page(topic)
                sofiaResponse1(ny.content[:500])
            else:
                return assistant(myCommand())
        except Exception as e:
            sofiaResponse(e)
    elif command:
        sofiaResponse1("Sorry i don't know that please try with these")
        print("""
            You can use these commands and I'll help you out:
    1. Open reddit subreddit : Opens the subreddit in default browser.
            2. Open xyz.com : replace xyz with any website name
            3. Send email/email : Follow up questions such as recipient name, content will be asked in order.
            4. Current weather in {cityname} : Tells you the current condition and temperture
            5. Hello
            6. play me a video : Plays song in your VLC media player
            7. change wallpaper : Change desktop wallpaper
            8. news for today : reads top news of today
            9. time : Current system time
            10. top stories from google news (RSS feeds)
            11. tell me about xyz : tells you about xyz
            """)
Ejemplo n.º 12
0
    oled.clear()
    now = time.time()
    if (now - last_input) < 10:
        if exit_menu:
            display_exit_screen()
        elif loading:
            display_loading_screen()
        else:
            display_main_screen()
    else:
        oled.display()
    if proceed:
        log("Track ended, scheduling next track")
        proceed = False
        vlc.next()
        vlc.play()
    time.sleep(0.1)

cleanup()
time.sleep(1)

if on_exit == REBOOT:
    #log("Rebooting device, bye!")
    #os.system("sudo shutdown -r now")
    os.system("/home/pi/workspace/whispery/whispery.py &")
    sys.exit(0)
elif on_exit == SHUTDOWN:
    log("Shutting down device, bye!")
    os.system("sudo shutdown -h now")
    sys.exit(0)
else:
Ejemplo n.º 13
0
def assistant(command):
    "if statements for executing commands"
#open subreddit Reddit
    if 'open reddit' in command:
        reg_ex = re.search('open reddit (.*)', command)
        url = 'https://www.reddit.com/'
        if reg_ex:
            subreddit = reg_ex.group(1)
            url = url + 'r/' + subreddit
        webbrowser.open(url)
        jarvisResponse('The Reddit content has been opened for you Sir.')
    elif 'tata' in command:
        jarvisResponse('Bye bye Sir. Have a nice day')
        sys.exit()
    elif 'thank you' in command:
        jarvisResponse('Bye bye Sir. Have a nice day')
        sys.exit()    
#open website
    elif 'open' in command:
        reg_ex = re.search('open (.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            print(domain)
            url = 'https://www.' + domain
            webbrowser.open(url)
            jarvisResponse(f'The website, {domain}, you have requested has been opened for you Sir.')
        else:
            pass
#greetings
    elif 'hello' in command:
        day_time = int(strftime('%H'))
        if 6 <= day_time < 12:
            jarvisResponse('Good morning. Hope you got some Sleep sir. And Sir, if you want to list my responsibilities, please say jobs!')
        elif 12 <= day_time < 18:
            jarvisResponse('Good afternoon. Jai Mata di, lets rock. And Sir, if you want to list my responsibilities, please say jobs!')
        elif 18 <= day_time < 21:
            jarvisResponse('Good evening. Jai Mata di, lets rock. And Sir, if you want to list my responsibilities, please say jobs!')
        else:
            jarvisResponse('Good Night. Please try to get some sleep Sir!')     
    elif 'jobs' in command:
        jarvisResponse("""
        My Responsibilities are:
            1.To greet you (command: Hello)
            2.To give you the current news(command: news for today)
            3.To respond with multiple jokes(command: joke)
            4.To open native apps(command: launch app)
            5.Open any website (command: Open website.com)
            6.To open SubReddits (command: open reddit subReddit)
            7.Send email, I will ask questions such as recipient name and content.(command: Send email)
            8.Tell you about Current weather conditions(command: Current weather in {weather})
            9.Play a video you desire(command: play me a video)
            10.To search for things on wikipedia(command: about topic)
            11.To respond with the current time (command: time)
            12.To leave you when you ask me to(command: bye)
            13.To Manipulate folders like create a new folder, remove folder etc.
        """)
#joke
    elif 'joke' in command:
        res = requests.get(
                'https://icanhazdadjoke.com/',
                headers={"Accept":"application/json"})
        if res.status_code == requests.codes.ok:
            jarvisResponse(str(res.json()['joke']))
        else:
            jarvisResponse('oops!I ran out of jokes')
#top stories from google news
    elif 'news' in command:
        try:
            news_url="https://news.google.com/news/rss"
            Client=urlopen(news_url)
            xml_page=Client.read()
            Client.close()
            soup_page=soup(xml_page,"lxml")
            news_list=soup_page.findAll("item")
            for news in news_list[:10]:
                jarvisResponse(news.title.text)#encode('utf-8'))
        except Exception as e:
                print(e)
#current weather
    elif 'current weather' in command: #NW
        reg_ex = re.search('current weather in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa')
            obs = owm.weather_at_place(city)
            w = obs.get_weather()
            k = w.get_status()
            x = w.get_temperature(unit='celsius')
            jarvisResponse('Current weather in %s is %s. The maximum temperature is %0.2f and the minimum temperature is %0.2f degree celcius' % (city, k, x['temp_max'], x['temp_min']))
#time
    elif 'time' in command:
        import datetime
        now = datetime.datetime.now()
        jarvisResponse('Current time is %d hours %d minutes' % (now.hour, now.minute))
    elif 'email' in command:
        jarvisResponse('Who is the recipient?')
        recipient = myCommand()
        if ' ' in recipient:
            jarvisResponse('What should I say to him?')
            content = myCommand()
            mail = smtplib.SMTP('smtp.gmail.com', 587)
            mail.ehlo()
            mail.starttls()
            mail.login('your_email_address', 'your_password')
            mail.sendmail('sender_email', 'receiver_email', content)
            mail.close()
            jarvisResponse('Email has been sent successfuly. You can check your inbox.')
        else:
            jarvisResponse('I don\'t know what you mean!')
#launch any application
    elif 'launch' in command:
        reg_ex = re.search('launch (.*)', command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname+".app"
            subprocess.Popen(["open", "-n", "/Applications/" + appname1], stdout=subprocess.PIPE)
        jarvisResponse(f'I have launched the {appname} application')
#play youtube song
    elif 'music' in command: #NW
        #path = '/Users/Apple/Documents/videos/'
        #folder = path
        #for the_file in os.listdir(folder):
        #    file_path = os.path.join(folder, the_file)
        #    try:
        #        if os.path.isfile(file_path):
        #            os.unlink(file_path)
        #    except Exception as e:
        #        print(e)
        jarvisResponse('What song shall I play Sir?')
        mysong = myCommand()
        if mysong:
            flag = 0
            url = "https://www.youtube.com/results?search_query=" + mysong.replace(' ', '+')
            response = urllib.request.urlopen(url)
            html = response.read()
            soup1 = soup(html,"lxml")
            url_list = []
            for vid in soup1.findAll(attrs={'class':'yt-uix-tile-link'}):
                if ('https://www.youtube.com' + vid['href']).startswith("https://www.youtube.com/watch?v="):
                    flag = 1
                    final_url = 'https://www.youtube.com' + vid['href']
                    url_list.append(final_url)
                    url = url_list[0]
                    ydl_opts = {}
                    os.chdir(path)
                with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                    ydl.download([url])
                vlc.play(path)
        if flag == 0:
            jarvisResponse('I have not found anything in Youtube ')
#change wallpaper
    elif 'change wallpaper' in command: #NW
        folder = '/Users/Apple/Documents/wallpaper/'
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
        api_key = 'fd66364c0ad9e0f8aabe54ec3cfbed0a947f3f4014ce3b841bf2ff6e20948795'
        url = 'https://api.unsplash.com/photos/random?client_id=' + api_key #pic from unspalsh.com
        f = urllib.urlopen(url)
        json_string = f.read()
        f.close()
        parsed_json = json.loads(json_string)
        photo = parsed_json['urls']['full']
        urllib.urlretrieve(photo, "/Users/Apple/Documents/wallpaper/a") # Location where we download the image to.
        subprocess.call(["killall Dock"], shell=True)
        jarvisResponse('wallpaper changed successfully')
#askme anything
    elif 'about' in command:
        reg_ex = re.search('about (.*)', command)
        try:
            if reg_ex:
                topic = reg_ex.group() #(1)
                ny = wikipedia.page(topic)
                jarvisResponse(ny.content[:1000])#.encode('utf-8')) #\n added
        except Exception as e:
                print(e)
    #elif 'greet' in command:
    #    jarvisResponse('Greetings Sweeney pie!')
    elif 'awesome' in command:
        jarvisResponse('Thank you sir!!!')
    #FILE MANIPULATION COMMANDS
    elif 'secret folder' in command:
        jarvisResponse('Working on a secret project are we sir?')
        proj = myCommand()
        if 'yes' in proj:
            os.mkdir('Desktop/NewProject')
            os.rename('Desktop/NewProject', 'Desktop/.NewProject')
            jarvisResponse('Secret Directory created sir!')
        elif 'no' in proj:
            jarvisResponse('Changing your mind sir? Sure.')
        elif 'delete' in proj:
            os.rmdir("Desktop/.NewProject")  
            os.chdir("..")  
            os.rmdir(".NewProject")  
            jarvisResponse('Directory Deleted Sir!')
        else:
            jarvisResponse('i dont understand sir')
    elif 'create folder' in command:
        os.mkdir('Desktop/NewProject')
        jarvisResponse('New Directory Created Sir!')
    elif 'remove folder' in command:
        jarvisResponse("Are you sure you want to delete it?")
        dele = myCommand()
        if 'yes' in dele:
            os.rmdir("Desktop/NewProject")  
            os.chdir("..")  
            os.rmdir("NewProject")  
            jarvisResponse('Directory Deleted Sir!')
        elif 'no' in dele:
            jarvisResponse("I am not deleting the Directory sir")
    elif 'list all files' in command:
        jarvisResponse('The following are the files sir!')
        startpath = os.getcwd()
        list_files(startpath)
    elif 'list files' in command:
        jarvisResponse('The following are the files in the Directory sir!')
        startpath = os.getcwd()
        list_files('Desktop/ChallengeDB')
    elif 'desktop files' in command:
        jarvisResponse('The following are the files in the Directory sir!')
        print(os.listdir('Desktop'))
    elif 'test' in command: #NW
        reg_ex = re.search('test (.*)', command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname+".py"
            subprocess.Popen(["open", "-n", "/Desktop/" + appname1], stdout=subprocess.PIPE)
        jarvisResponse(f'I have launched the {appname} application')
    elif 'play' in command: #NW
        lz_uri = 'spotify:artist:36QJpDe2go2KgaRleHCDTp'

        spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
        results = spotify.artist_top_tracks(lz_uri)

        for track in results['tracks'][:10]:
            print('track    : ' + track['name'])
            print('audio    : ' + track['preview_url'])
            print('cover art: ' + track['album']['images'][0]['url'])
            print()
Ejemplo n.º 14
0
def assistant(command):
    "if statements for executing commands"
    #open subreddit Reddit
    if 'open reddit' in command:
        reg_ex = re.search('open reddit (.*)', command)
        url = 'https://www.reddit.com/'
        if reg_ex:
            subreddit = reg_ex.group(1)
            url = url + 'r/' + subreddit
        webbrowser.open(url)
        sofiaResponse('The Reddit content has been opened for you.')
    elif 'shutdown' in command:
        sofiaResponse('Bye Bye. Have a nice day')
    elif 'open' in command:
        reg_ex = re.search('open(.+)', command)
        if reg_ex:
            domain = reg_ex.group(1)
            domain = domain.strip()
            print(domain)
            url = 'https://www.' + domain
            webbrowser.open(url)
            sofiaResponse(
                'The website you hae requested has been opened for you sir.')
        else:
            pass
    elif 'help me' in command:
        sofiaResponse(""" You can use these commands and I'll help you out:
            1. Open reddit subreddit : Opens the subreddit in default browser.
            2. Open any website
            3. Send email/email : Follow up questions such as recipient name, content will be asked in order.
            4. Current weather in {cityname} : Tells you the current condition and temperature
            5. Hello
            6. Play a video : Plays song in your VLC media player
            7. change wallpaper : Change desktop wallpaper
            8. news for today : reads top news of today
            9. time : Current system time
            10. top stories from google news (RSS feeds)
            11. tell me about anything
            """)
    elif 'joke' in command:
        res = requests.get('https://icanhazdadjoke.com/',
                           headers={"Accept": "application/json"})
        if res.status_code == requests.codes.ok:
            sofiaResponse(str(res.json()['joke']))
        else:
            sofiaResponse('oops! I ran out of jokes')
    elif 'news for today' in command:
        try:
            news_url = "https://news.google.com/news/rss"
            Client = urlopen(news_url)
            xml_page = Client.read()
            Client.close()
            soup_page = soup(xml_page, "xml")
            news_list = soup_page.findAll("item")
            for news in news_list[:15]:
                sofiaResponse(news.title.text.encode('utf-8'))
        except Exception as e:
            print(e)
    elif 'current weather' in command:
        reg_ex = re.search('current weather in (.*)', command)
        if reg_ex:
            city = reg_ex.group(1)
            owm = OWM(API_key='ab0d5e80e8dafb2cb81fa9e82431c1fa')
            obs = owm.weather_at_place(city)
            w = obs.get_weather()
            k = w.get_status()
            x = w.get_temperature(unit='celcius')
            sofiaResponse(
                'Current weather in %s is %s. The maximum temperatue is %0.2f and the minimum temperature is %0.2f degree celcius'
                % (city, k, x['temp_max'], x['temp_min']))
    elif 'time' in command:
        import datetime
        now = datetime.datetime.now()
        sofiaResponse('Current time is %d hours %d minutes' %
                      (now.hour, now.minute))
    elif 'email' in command:
        sofiaResponse('Who is the recipient?')
        recipient = myCommand()
        if 'rajat' in recipient:
            sofiaResponse('What should I say to him?')
            content = myCommand()
            mail = smtplib.SMTP('smtp.gmail.com', 587)
            mail.ehlo()
            mail.starttls()
            mail.login('your_email_address', 'your_password')
            mail.sendmail('sender_email', 'receiver_email', content)
            mail.close()
            sofiaResponse(
                'Email has been sent successfully. You can check your inbox.')
        else:
            sofiaResponse('I don\'t know what you mean!')
    elif 'launch' in command:
        reg_ex = re.search('launch (.*)', command)
        if reg_ex:
            appname = reg_ex.group(1)
            appname1 = appname + ".app"
            subprocess.Popen(["open", "-n", "/Application/" + appname1],
                             stdout=subprocess.PIPE)
            sofiaResponse('I have launched the desired application')
    elif 'play me a song' in command:
        path = '/Users/sathvik/Downloads/videos/'
        folder = path
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
        sofiaResponse('What song shall I play?')
        mysong = myCommand()
        if mysong:
            flag = 0
            url = "http://www.youtube.com/results?search_query=" + mysong.replace(
                ' ', '+')
            response = urllib2.urlopen(url)
            html = response.read()
            soup1 = soup(html, "lxml")
            url_list = []
            for vid in soup1.findAll(attrs={'class': 'yt-uix-tile-link'}):
                if ('https://www.youtube.com' + vid['href']
                    ).startswith("https://www.youtube.com/watch?v="):
                    flag = 1
                    final_url = 'https://www.youtube.com' + vid['href']
                    url_list.append(final_url)
                    url = url_list[0]
                    ydl_opts = {}
                    os.chdir(path)
                    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                        ydl.download([url])
                        vlc.play(path)
            if flag == 0:
                sofiaResponse('I have not found anything in Youtube')
    elif 'change wallpaper' in command:
        folder = '/Users/sathvik/Documents/wallpaper/'
        for the_file in os.listdir(folder):
            file_path = os.path.join(folder, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
            except Exception as e:
                print(e)
        api_key = 'fd66364c0ad9e0f8aabe54ec3cfbed0a947f3f4014ce3b841bf2ff6e20948795'
        url = 'https://api.unsplash.com/photos/random?client_id=' + api_key
        f = urllib2.urlopen(url)
        json_string = f.read()
        f.close()
        parsed_json = json.loads(json_string)
        photo = parsed_json['urls']['full']
        urllib.urlretrieve(photo, "/Users/sathvik/Documents/wallpaper/a")
        subprocess.call(["killall Dock"], shell=True)
        sofiaResponse('Wallpaper changed successfully')
    elif 'tell me about' in command:
        reg_ex = re.search('tell me about (.*)', command)
        try:
            if reg_ex:
                topic = reg_ex.group(1)
                ny = wikipedia.page(topic)
                sofiaResponse(ny.content[:500].encode('utf-8'))
        except Exception as e:
            print(e)
            sofiaResponse(e)
    sofiaResponse(
        'Hey, i am Sofia and I am your personal voice assistant, Please give a command or say "help me and I will tell you what all I can do for you.'
    )
    while True:
        assistant(myCommand())
Ejemplo n.º 15
0
        output_file = kvargs['output_file']
    else:
        output_file = 'output.mp3'

    if len(words) == 0:
        usage()

    word_list = []

    print(words)

    for word in words:
        if os.path.isfile(word):
            word_list.append(AudioSegment.from_mp3(word))
        else:
            usage("Word is not a valid path to mp3!")

    # Concatenation is just adding
    chunk = 100
    word = word_list[0][chunk:]
    sentence = word[:len(word) - chunk]
    for word in word_list[1:]:
        temp = word[chunk:]
        sentence += temp[:len(temp) - chunk]

    # writing mp3 files is a one liner
    sentence.export("sentence.mp3", format="mp3")

    vlc.play(
        "/Users/griffin/Code/Courses/1-Current_Courses/4883-Software-Tools/Resources/morse_code/sentence.mp3"
    )