athrvvvv / AppOpener

Python library to open/close applications in windows.
https://appopener.readthedocs.io/en/latest/
MIT License
18 stars 7 forks source link

Match Closest Not Working #18

Closed Ayanotaro closed 1 year ago

Ayanotaro commented 1 year ago

I was trying to implement this library in my chatbot but even if i use the match_closest command the app wouldn't open is there anything i can do?

` import subprocess,requests,wolframalpha,json,datetime,wikipedia,webbrowser,os,winshell,pyjokes,smtplib,ctypes,time,winsound,pyautogui,time import speech_recognition as sr from urllib.request import urlopen import customtkinter as ctk import pyttsx3 as p from AppOpener import open, close

class App(ctk.CTk): def init(self, *args, *kwargs): super().init( args, **kwargs)

def runchatbot(app): engine = p.init('sapi5') rate = engine.getProperty('rate') engine.setProperty('rate', 180) voices = engine.getProperty('voices') engine.setProperty('voices', voices[0].id)

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour >= 0 and hour < 12:
        speak("Good Morning  !")

    elif hour >= 12 and hour < 18:
        speak("Good Afternoon  !")

    else:
        speak("Good Evening  !")

    assname = ("Charlie")
    speak("I am your Assistant")
    speak(assname)

    speak("How can i Help you")

def takeCommand():

    r = sr.Recognizer()

    with sr.Microphone() as source:
        ready()
        r.energy_threshold = 5000
        r.adjust_for_ambient_noise(source, 1)
        print("Listening......")
        audio = r.listen(source)
        ready1()

    try:
        print("Recognizing...")
        query = r.recognize_google(audio)
        print(f"User said: {query}\n")

    except Exception as e:
        print(e)
        print("Unable to Recognize your voice.")
        return "None"

    return query

def ready():
    winsound.Beep(600,300)

def ready1():
    winsound.Beep(500,200)

def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()

    server.login('amanjotsingh000013@gmail.com', 'gtrvdssceijeqozp')
    server.sendmail('amanjotsingh00013@gmail.com', to, content)
    server.close()

if __name__ ==  '__main__':
    clear = lambda: os.system('cls') 

    clear()
    wishMe()

    while True:

        query = str(takeCommand()).lower()

        if 'information' in query:
            speak('Searching your query in my database...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=3)
            speak("According to my database")
            print(results)
            speak(results)

        elif 'open app' in query:
            speak("Which app do you want to open?")
            APP = takeCommand()
            open(APP, match_closest=True)

        elif 'open google' in query:
            speak("Here you go to Google\n")
            webbrowser.open("google.com")

        elif 'open stackoverflow' in query:
            speak("Here you go to Stack Over flow.Happy coding")
            webbrowser.open("stackoverflow.com")

        elif 'open url' in query:
            speak("Tell me the url you want to open.")
            url_ = takeCommand()
            speak("Alright opening " + str(url_))
            webbrowser.open(str(url_))

        elif 'play music' in query or "play song" in query:
            speak("Here you go with music")

            music_dir = "C:\\Users\\GAURAV\\Music"
            songs = os.listdir(music_dir)
            print(songs)
            random = os.startfile(os.path.join(music_dir, songs[1]))

        elif 'the time' in query or 'time' in query:
            strTime = datetime.datetime.now().strftime("%H:%M:%S")
            speak(f"Sir, the time is {strTime}")

        elif 'open edge' in query:
            codePath = r"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe"
            os.startfile(codePath)

        elif 'open notepad' in query:
            codePath = r"C:\\WINDOWS\\system32\\notepad.exe"
            os.startfile(codePath)

        elif 'email to gaurav' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                to = "Receiver email address"
                sendEmail(to, content)
                speak("Email has been sent !")
            except Exception as e:
                print(e)
                speak("I am not able to send this email")

        elif 'send a mail' in query:
            try:
                speak("What should I say?")
                content = takeCommand()
                speak("whome should i send")
                to = input("enter the mail: ")
                sendEmail(to, content)
                speak("Email has been sent !")
            except Exception as e:
                print(e)
                speak("I am not able to send this email")

        elif 'how are you' in query:
            speak("I am fine, Thank you")
            speak("How are you, Sir")

        elif 'click on the search bar' in query:
            speak("Done Sir")
            pyautogui.click(556, 84)

        elif 'type' in query:
            speak("Ok sir, What you want to write")
            matter = takeCommand()
            pyautogui.typewrite(matter, interval=0.25)

        elif 'press Enter' in query:
            speak("Enter Pressed")
            pyautogui.keyDown('enter')
            pyautogui.keyUp('enter')

        elif 'press backspace' in query:
            speak("Backspace Pressed")
            pyautogui.keyDown('backspace')
            pyautogui.keyUp('backspace')

        elif 'select all' in query:
            speak("Selected")
            pyautogui.keyDown('ctrl')
            pyautogui.press('A')
            pyautogui.keyUp('ctrl')

        elif 'copy' in query:
            speak("Copied")
            pyautogui.keyDown('ctrl')
            pyautogui.press('C')
            pyautogui.keyUp('ctrl')

        elif 'paste' in query:
            speak("Pasted")
            pyautogui.keyDown('ctrl')
            pyautogui.press('V')
            pyautogui.keyUp('ctrl')

        elif 'switch tab' in query:
            speak("Switched")
            pyautogui.keyDown('alt')
            pyautogui.press('tab')
            pyautogui.keyUp('alt')

        elif 'fine' in query or "good" in query:
            speak("It's good to know that your fine")

        elif "change my name to" in query:
            query = query.replace("change my name to", "")
            assname = query

        elif "change name" in query:
            speak("What would you like to call me, Sir ")
            assname = takeCommand()
            speak("Thanks for naming me")

        elif "what's your name" in query or "What is your name" in query:
            speak("My friends call me")
            speak("charlie")
            print("My friends call me charlie")

        elif 'exit' in query:
            speak("Thanks for giving me your time")
            exit()

        elif 'joke' in query:
            speak(pyjokes.get_joke())

        elif "calculate" in query:

            appid = 'VQ7XRG-W5VUXE6G45'
            client = wolframalpha.Client(appid)
            indx = query.lower().split().index('calculate')
            query = query.split()[indx + 1:]
            res = client.query(' '.join(query))
            answer = next(res.results).text
            print("The answer is " + answer)
            speak("The answer is " + answer)

        elif 'search' in query or 'play' in query:

            query = query.replace("search", "")
            query = query.replace("play", "")
            webbrowser.open(query)

        elif "who i am" in query:
            speak("If you talk then definitely your human.")

        elif "why you came to world" in query:
            speak("Thanks to Amanjot Singh. further It's a secret")

        elif 'power point presntation' in query:
            speak("opening Power Point presentation")
            power = r"C:\\Users\\GAURAV\\Desktop\\Minor Project\\Presentation\\Voice Assistant.pptx"
            os.startfile(power)

        elif "assignments" in query:
            speak("Here are your all assignments sir")
            url = ""

        elif "who are you" in query:
            speak("I am your virtual assistant, named Charlie, created by Amanjot Singh")

        elif 'reason for you' in query:
            speak("I was created as a Minor project by Mister Amanjot Singh ")

        elif 'change background' in query:
            ctypes.windll.user32.SystemParametersInfoW(20,
                                                    0,
                                                    "Location of wallpaper",
                                                    0)
            speak("Background changed successfully")

        elif 'news' in query:

            try:
                jsonObj = urlopen(
                    '''https://newsapi.org/v2/top-headlines?country=in&apiKey=51ea3c4a97c34dd59e57df84c8f815dd''')
                data = json.load(jsonObj)
                i = 1

                speak('here are some top news ')
                print('''=====================================================''' + '\n')

                for item in data['articles']:
                    print(str(i) + '. ' + item['title'] + '\n')
                    print(item['description'] + '\n')
                    speak(str(i) + '. ' + item['title'] + '\n')
                    i += 1
            except Exception as e:

                print(str(e))

        elif 'lock window' in query:
            speak("locking the device")
            ctypes.windll.user32.LockWorkStation()

        elif 'shutdown system' in query:
            speak("Hold On a Sec ! Your system is on its way to shut down")
            subprocess.call('shutdown / p /f')

        elif 'empty recycle bin' in query:
            winshell.recycle_bin().empty(confirm=False, show_progress=False, sound=True)
            speak("Recycle Bin Recycled")

        elif "don't listen" in query or "stop listening" in query:
            speak("for how much time you want to stop charlie from listening commands")
            a = str(takeCommand())
            time.sleep(int(a))
            print(a)

        elif "where is" in query:
            query = query.replace("where is", "")
            location = query
            speak("User asked to Locate")
            speak(location)
            webbrowser.open("https://www.google.nl / maps / place/" + location + "")

        elif "restart" in query:
            subprocess.call(["shutdown", "/r"])

        elif "hibernate" in query or "sleep" in query:
            speak("Hibernating")
            subprocess.call("shutdown / h")

        elif "log off" in query or "sign out" in query:
            speak("Make sure all the application are closed before sign-out")
            time.sleep(5)
            subprocess.call(["shutdown", "/l"])

        elif "write a note" in query or "write me a note" in query or "write me the note" in query:
            speak("What should i write, sir")
            note = str(takeCommand())
            file = open('charlie.txt', 'w')
            speak("Sir, Should i include date and time")
            snfm = takeCommand()

            if 'yes' in snfm or 'sure' in snfm:
                strTime = datetime.datetime.now().strftime("%H:%M:%S")
                file.write(strTime)
                file.write(" :- ")
                file.write(note)
            else:
                file.write(note)

        elif "show notes" in query or "show me notes" in query or "show note" in query:
            speak("Showing Notes")
            file = open("charlie.txt", "r")
            print(file.read())
            speak(file.read(6))

        elif "charlie" in query:

            speak("In your service SIR")

        elif "weather" in query:

            api_key = "3441f2269216535d2db5195ad061aed2"
            base_url = "http://api.openweathermap.org/data/2.5/weather?"
            city_name = "ludhiana"
            complete_url = base_url + "appid=" + api_key + "&q=" + city_name
            response = requests.get(complete_url)
            x = response.json()

            if x["cod"] != "404":

                y = x["main"]
                current_temperature = y["temp"]
                current_pressure = y["pressure"]
                current_humidiy = y["humidity"]
                z = x['weather']
                weather_description = z[0]["description"]
                print(" Temperature (in kelvin unit) = " + str(
                    current_temperature) + "\n atmospheric pressure (in hPa unit) =" + str(
                    current_pressure) + "\n humidity (in percentage) = " + str(current_humidiy) + "\n description = " + str(
                    weather_description))
                speak(" Temperature (in kelvin unit) = " + str(
                    current_temperature) + "\n atmospheric pressure (in hPa unit) =" + str(
                    current_pressure) + "\n humidity (in percentage) = " + str(current_humidiy) + "\n description = " + str(
                    weather_description))

            else:
                speak(" City Not Found ")

        elif "wikipedia" in query:
            webbrowser.open("wikipedia.com")

        elif "good morning" in query:
            speak("A warm" + query+ "Sir")

        elif "good afternoon" in query:
            speak("A warm" + query+ "Sir")

        elif "good evening" in query:
            speak("A warm" + query + "Sir")

        elif "how are you" in query:
            speak("I'm fine, glad you me that")

        elif "what is" in query or "who is" in query or "what are" in query or "who are" in query:

            app_id = 'VQ7XRG-W5VUXE6G45'
            client = wolframalpha.Client(app_id)
            res = client.query(query)

            try:
                print(next(res.results).text)
                speak(next(res.results).text)
            except StopIteration:
                print("No results")

        elif "scroll down" in query:
            pyautogui.scroll(-500)
            speak("scrolled down Sir")

        elif "scroll up" in query:
            pyautogui.scroll(500)
            speak("scrolled up Sir")

        elif "about you" in query or "about yourself" in query:
            print("My name is Charlie and I am A intelligent voice assistant. I can do whatever you tell me to do. Your wish is my command. I got a life and can be in at your presence only because of my creator sir, Amanjot Singh Makkar")
            speak("My name is Charlie and I am A intelligent voice assistant. I can do whatever you tell me to do. Your wish is my command. I got a life and can be in at your presence only because of my creator sir, Amanjot Singh Makkar")

        elif "what can you do" in query:
            print("I can do various things:"
                "here are top commands"
                "1. I can control your computer ie you can tell me to type for you, open your softwares, copy and paste for you"
                "2. I can search for you from my database and tell about that even faster than your typing skills"
                "3. I can calculate anything for you, even that things also that calculator cant do it"
                "4. I can tell you the latest NEWS and keep you the update")
            speak("I can do various things:"
                "here are top commands"
                "1. I can control your computer ie you can tell me to type for you, open your softwares, copy and paste for you"
                "2. I can search for you from my database and tell about that even faster than your typing skills"
                "3. I can calculate anything for you, even that things also that calculator cant do it"
                "4. I can tell you the latest NEWS and keep you the update")

app = App()

button = ctk.CTkButton(app, command=lambda: runchatbot(app)).grid(row=0,column=0) app.mainloop()`

athrvvvv commented 1 year ago

Actually instead of copying and pasting the whole code, you should show the error you have got?!

For now try this:

from AppOpener import open as run, close

elif 'open app' in query:
    speak("Which app do you want to open?")
    APP = takeCommand()
    run(str(APP), match_closest=True)

Do tell me if this works 🤝

Ayanotaro commented 1 year ago

Sorry For The Late Reply I Am New To Github But Thanks It's Fixed Really Thanks