예제 #1
0
파일: news.py 프로젝트: parthjetani/Vision
def news(query):
    idx = query.split().index('news')
    query = query.split()[idx + 1:]
    params = None
    if len(query) < 3:
        if 'country' in query[0]:
            if query[1] in this_dict:
                params = {'country': this_dict[query[1]], 'apiKey': apikey}

        else:
            params = {'category': query[1], 'apiKey': apikey}

    else:
        if 'country' in query[0]:
            params = {
                'country': this_dict[query[1]],
                'category': query[3],
                'apiKey': apikey
            }

    url = "https://newsapi.org/v2/top-headlines?"

    url_parts = list(urlparse.urlparse(url))
    query = dict(urlparse.parse_qsl(url_parts[4]))
    query.update(params)

    url_parts[4] = urlencode(query)
    response = requests.get(urlparse.urlunparse(url_parts)).json()

    for new in response["articles"]:
        print(str(new['title']))
        vision.speak(new['title'])
예제 #2
0
def WolframSkills(cmd):
    """
    Make a request in wolfram Alpha API and prints the response.
    """
    client = wolframalpha.Client(WOLFRAMALPHA_API['key'])
    try:
        if WOLFRAMALPHA_API['key']:
            vision.speak("Wait a second, I search..")
            res = client.query(cmd)
            wolfram_result = next(res.results).text
            vision.speak(f"The Answer Is {wolfram_result}")
        else:
            vision.speak(
                "WolframAlpha API is not working.\n"
                "You can get an API key from: https://developer.wolframalpha.com/portal/myapps/ "
            )

    except Exception as e:
        if netinfo.ConnectionCheck():
            # If there is an error but the internet connect is good, then the Wolfram API has problem
            vision.speak(
                'There is no result from Wolfram API with error: {0}'.format(
                    e))
        else:
            vision.speak('Sorry, but I could not find something')
예제 #3
0
def print_weather(result, cty):
    vision.speak("{}'s temperature: {}°C ".format(cty, result['main']['temp']))
    vision.speak("Wind speed: {} meter per second".format(
        result['wind']['speed']))
    vision.speak("Description: {}".format(result['weather'][0]['description']))
    vision.speak("Weather: {}".format(result['weather'][0]['main']))
    vision.speak("Visibility:{} kilometer".format(result['visibility'] / 1000))
예제 #4
0
def main(txt):

    try:
        txt = txt.split()
        for i in range(len(city)):
            if city[i] in txt:
                query = 'q=' + city[i]
                w_data = weather_data(query)
                print_weather(w_data, city[i])
    except ArithmeticError:
        vision.speak('City name not found...')
예제 #5
0
def InternetConnection():
    vision.speak("Checking internet connection...")
    if ConnectionCheck():
        vision.speak("You are connected to internet...")
    else:
        vision.speak("You are not connected to internet...")
        vision.speak("Please connect first...")
    return
예제 #6
0
def mail():
    # Write here sender email address and password
    sender_email = "sender email address"
    password = "******"

    vision.speak("Who do you want to email? ")
    receiver = vision.command()

    if receiver in mail_address:
        receiver_email = mail_address[receiver]

        message = MIMEMultipart("alternative")
        message["From"] = sender_email
        message["To"] = receiver_email

        # This is for email subject
        vision.speak(f"Got it, you want to email {receiver}.\n"
                     f"What's the Subject?")
        subject = vision.command()

        # Create the plain-text version of your message
        vision.speak(f"Got it, What's the message?")
        text = vision.command()

        # Turn these into plain/html MIMEText objects
        part1 = MIMEText(text, "plain")

        # Add plain-text parts to MIMEMultipart message
        # The email client will try to render the last part first
        message.attach(part1)
        message["Subject"] = subject

        try:
            # Create secure connection with server and send email
            context = ssl.create_default_context()

            with smtplib.SMTP_SSL("smtp.gmail.com", 465,
                                  context=context) as server:
                server.login(sender_email, password)
                server.sendmail(sender_email, receiver_email,
                                message.as_string())
                vision.speak("Sir I have successfully send mail..")

        except smtplib.SMTPException:
            vision.speak("Error: unable to send email")
예제 #7
0
def search_web(cmd):
    if 'youtube' in cmd:
        vision.speak("Opening in youtube")
        idx = cmd.split().index('youtube')
        txt = cmd.split()[idx + 1:]
        search_keyword = urllib.parse.urlencode({'search_query': txt})
        html = urllib.request.urlopen("https://www.youtube.com/results?" + search_keyword)
        video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())
        webbrowser.open("https://www.youtube.com/watch?v=" + video_ids[0])
        time.sleep(5)
        return

    elif 'wikipedia' in cmd:

        vision.speak("Opening Wikipedia")
        idx = cmd.split().index('wikipedia')
        txt = cmd.split()[idx + 1:]
        webbrowser.open("https://en.wikipedia.org/wiki/" + '_'.join(txt))
        time.sleep(5)
        return

    else:

        if 'google' in cmd:
            vision.speak("Searching on Google")
            idx = cmd.split().index('google')
            txt = cmd.split()[idx + 1:]
            webbrowser.open("https://www.google.com/search?q=" + '+'.join(txt))
            time.sleep(5)

        elif 'search' in cmd:
            vision.speak("Searching on Google")
            idx = cmd.split().index('search')
            txt = cmd.split()[idx + 1:]
            webbrowser.open("https://www.google.com/search?q=" + '+'.join(txt))
            time.sleep(5)

        else:
            vision.speak("Searching on Google")
            webbrowser.open("https://www.google.com/search?q=" + '+'.join(cmd.split()))
            time.sleep(5)
예제 #8
0
def location():
    try:
        res = requests.get('https://ipinfo.io?token=' + token_number)
        data = res.json()
        country = data['country']
        loc = data['loc'].split(',')

        if 'IN' in country:
            country = 'India'

        vision.speak("Your latitude: {} , longitude: {}".format(
            loc[0], loc[1]))
        vision.speak("You are currently in {}, {}, {}".format(
            data['city'], data['region'], country))
        vision.speak("Your timezone is {}".format(data['timezone']))

    except ConnectionError as e:
        vision.speak(
            "Unable to get current location with error message: {0}".format(e))
    return
예제 #9
0
def AssistantSkill(cmd):
    try:
        if vision.split(cmd) in web_dict:
            search.search_web(cmd)
            return

        elif cmd in media_toggle[0]:
            vision.speak("opening your music player")
            mediaplayer.music()
            return

        elif cmd in media_toggle[1]:
            vision.speak("opening your video player")
            mediaplayer.video()
            return

        elif 'send email' in cmd or 'sent mail' in cmd:
            mail.mail()
            return

        elif "who are you" in cmd or "define yourself" in cmd:
            speaks = '''Hello, I am Person. Your personal Assistant. I am here to make your life easier. You can 
            command me to perform various tasks such as calculating sums or opening applications etc '''
            vision.speak(speaks)
            return

        elif "who made you" in cmd or "created you" in cmd:
            speaks = "I have been created by Developer."
            vision.speak(speaks)
            return

        elif "calculate" in cmd.lower():
            wolframalph.WolframSkills(cmd)
            return

        elif cmd in frequent[1]:
            date_time.tell_the_date()
            return

        elif cmd in frequent[0]:
            date_time.tell_the_time()
            return

        elif cmd in system_toggle:
            systeminfo.SystemInfo()
            return

        elif 'network speed' in cmd:
            netinfo.Speed()
            return

        elif 'check internet connection' in cmd:
            netinfo.InternetConnection()
            return

        elif 'open' in cmd:
            desktopapps.open_application(cmd)
            return

        elif 'close' in cmd:
            desktopapps.close_application(cmd)
            return

        elif 'news' in cmd:
            news.news(cmd)
            return

        elif "weather" in cmd:
            weather.main(cmd)
            return

        elif cmd in whereAbouts:
            location.location()
            return

        elif "shutdown" in cmd:
            os.system("shutdown /s /t 1")
            return

        elif "restart" in cmd:
            os.system("shutdown /r /t 1")
            return

        else:
            vision.speak("Please check my skill listed in info file...")
            return

    except Exception as e:
        vision.speak(e)
        return
예제 #10
0
def Speed():
    st = speedtest.Speedtest()
    vision.speak("What speed do you want to test?")
    txt = vision.command()
    if 'download' in txt:
        vision.speak("Checking download speed...")
        vision.speak("your download speed is %d Mbps" % (st.download() /
                                                         (10**6)))
    elif 'upload' in txt:
        vision.speak("Checking upload speed...")
        vision.speak("your upload speed is %d Mbps" % (st.upload() / (10**6)))
    elif 'ping' in txt:
        server_name = []
        st.get_servers(server_name)
        vision.speak("%d ms" % st.results.ping)
    return
예제 #11
0
def close_application(cmd):
    if "word" in cmd:
        vision.speak("Closing Microsoft Word")
        os.system("TASKKILL /F /IM WINWORD.EXE")
        return

    elif "excel" in cmd:
        vision.speak("Closing Microsoft Excel")
        os.system("TASKKILL /F /IM EXCEL.EXE")
        return

    elif "power point" in cmd:
        vision.speak("Closing Microsoft Power Point")
        os.system("TASKKILL /F /IM POWERPNT.EXE")
        return

    elif "calculator" in cmd:
        vision.speak("Closing calculator")
        os.system("TASKKILL /F /IM calculator.exe")
        return

    elif "cmd" in cmd:
        vision.speak("Closing cmd")
        os.system("TASKKILL /F /IM cmd.exe")
        return

    elif "control panel" in cmd:
        vision.speak("Closing control panel")
        os.startfile('C:\\Windows\\System32\\control.exe')
        return

    elif "visual code" in cmd:
        vision.speak("Closing Microsoft Visual Code")
        os.system("TASKKILL /F /IM code.exe")

    else:
        vision.speak("Application not available")
        return
예제 #12
0
def open_application(cmd):
    if "word" in cmd:
        vision.speak("Opening Microsoft Word")
        os.startfile(
            'C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Word.lnk'
        )
        return

    elif "excel" in cmd:
        vision.speak("Opening Microsoft Excel")
        os.startfile(
            'C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Excel.lnk'
        )
        return

    elif "power point" in cmd:
        vision.speak("Opening Microsoft Power Point")
        os.startfile(
            'C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\PowerPoint.lnk'
        )
        return

    elif "calculator" in cmd:
        vision.speak("Opening calculator")
        os.startfile('C:\\Windows\\System32\\calc.exe')
        return

    elif "cmd" in cmd:
        vision.speak("Opening cmd")
        os.startfile('C:\\Windows\\System32\\cmd.exe')
        return

    elif "task manager" in cmd:
        vision.speak("Opening task manager")
        os.startfile('C:\\Windows\\System32\\Taskmgr.exe')
        return

    elif "visual code" in cmd:
        vision.speak("Opening Microsoft Visual Code")
        os.startfile(
            'C:\\Users\\Paras Jetani\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe'
        )

    else:
        vision.speak("Application not available")
        return
예제 #13
0
def SystemInfo():
    def get_size(bytes, suffix="B"):
        factor = 1024
        for unit in ["", "K", "M", "G", "T", "P"]:
            if bytes < factor:
                return f"{bytes:.2f}{unit}{suffix}"
            bytes /= factor

    # System Information
    uname = platform.uname()

    vision.speak("System Information")
    vision.speak(
        f"System {uname.system}, Version {uname.version}, "
        f"Machine {uname.machine}, Processor {uname.processor}, Node Name {uname.node}"
    )

    # CPU Information
    cpu_freq = psutil.cpu_freq()

    vision.speak("CPU Information")
    vision.speak(
        f"Total Number Of CPU Cores: {psutil.cpu_count(logical=True)}, "
        f"Current CPU Frequency: {cpu_freq.current:.2f}Mhz, Total CPU Usage: {psutil.cpu_percent()}%"
    )

    # Memory Information
    memory = psutil.virtual_memory()

    vision.speak("Memory Information")
    vision.speak(
        f"Total Memory Size: {get_size(memory.total)}, Total Free Memory: {get_size(memory.available)}, "
        f"Total Used Memory: {get_size(memory.used)}")

    # Disk Information
    par_t = 0
    par_u = 0
    par_f = 0

    partitions = psutil.disk_partitions()

    for partition in partitions:
        try:
            partition_usage = psutil.disk_usage(partition.mountpoint)
        except PermissionError:
            # this can be catched due to the disk that
            # isn't ready
            continue

        par_t = par_t + partition_usage.total
        par_u = par_u + partition_usage.used
        par_f = par_f + partition_usage.free

    vision.speak("Disk Information")
    vision.speak(
        f"Total Size Of Your Disk: {get_size(par_t)}, "
        f"Currently Used Disk Size: {get_size(par_u)}, Currently Free Disk Size: {get_size(par_f)}"
    )

    # Battery information
    battery = psutil.sensors_battery()
    plugged = battery.power_plugged
    percent = str(battery.percent)

    if not plugged:
        vision.speak(
            f"Currently Your Battery Is {percent}% And Not Plugged In")

    else:
        vision.speak(f"Currently Your Battery Is {percent}% And Plugged In")

    return
예제 #14
0
def tell_the_time():
    now = datetime.now()
    hour, minute = now.hour, now.minute
    converted_time = _time_in_text(hour, minute)
    vision.speak('The current time is: {0}'.format(converted_time))
예제 #15
0
def tell_the_date():
    today = date.today()
    vision.speak('The current date is: {0}'.format(today))