Giter VIP home page Giter VIP logo

appopener's Introduction

AppOpener ๐Ÿ”“

AppOpener is the python library to open/close any application without knowing it's absoulute path. The library works by making use of App Name and App Id.

Library works on python version 3.5 or above python version 3.5+

PyPI Downloads ย  PyPI Downloads ย  PyPI Downloads ย  Windows Only

Visit official documentation of AppOpener here.

The latest development version is always available at the Github repository.


Features:

  1. Open applications
  2. Close applicatons
  3. Create list of Apps & Ids

Integrating AppOpener

See Examples for more.

Install Package ๐Ÿ“ฆ

pip install AppOpener

Quick start โšก

from AppOpener import open, close, mklist, give_appnames
open("telegram, whatsapp") # Opens telegram and whatsapp
open("APPNAME", throw_error=True) # Raises Exception if App is not found (can be used in `close` function too)
close("telgrm", match_closest=True) # Closes telegram as "telgrm" is closest to "telegram"
mklist(name="app_data.json") # Generates an file, having key as AppName and value as AppIds.
appnames = give_appnames() # Save appnames as dictionary

Building package ๐Ÿ”จ

git clone https://github.com/athrvvvv/AppOpener.git
cd AppOpener
python setup.py sdist bdist_wheel

The latest release is always available at the Github releases.


Contributing ๐Ÿค

Contributions are welcomed. To know more visit here.


Links ๐Ÿ”—

Stay connected ๐Ÿค—

appopener's People

Contributors

athrvvvv avatar guleri24 avatar kalyan19111999 avatar merksk8 avatar sahil481 avatar userjoo9 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

appopener's Issues

Match Closest Not Working

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('[email protected]', 'gtrvdssceijeqozp')
    server.sendmail('[email protected]', 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()`

site-packages\\AppOpener\\Data\\reference.txt

FileNotFoundError: [Errno 2] No such file or directory: 'C:\Users\aadhi\AppData\Local\Programs\Python\Python310\lib\site-packages\AppOpener\Data\reference.txt'

Iam unable to import AppOpener

TypeError: the JSON object must be str, bytes or bytearray, not NoneType

""" File "C:\Users\dingj\Desktop\testtt\new\main.py", line 5, in
from AppOpener import open
File "C:\Users\dingj\Desktop\testtt\new\venv\Lib\site-packages\AppOpener_init_.py", line 7, in
check.check_json()
File "C:\Users\dingj\Desktop\testtt\new\venv\Lib\site-packages\AppOpener\check.py", line 63, in check_json
create_file()
File "C:\Users\dingj\Desktop\testtt\new\venv\Lib\site-packages\AppOpener\check.py", line 53, in create_file
apps = json.loads(result.stdout)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\dingj\AppData\Local\Programs\Python\Python311\Lib\json_init_.py", line 339, in loads
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not NoneType

Process finished with exit code 1
"""
Using pycharm

Microsoft store is not closing

when i open microsoft store using open() method it works but when i try close() method to close microsoft store it show microsoft is not running even if it is running everytime.
it has the same problem with winrar,microsoft to do also

How do I add an exception? if Appname is not found

The app opener when using the open() function does not throw an error and rather prints to terminal. This makes it hard to do certain things such as speak something using speech recognition library when like the app is not found

Need to install `pywin32` to get working on Windows 10

I ran into an error after installing with pip saying that it couldn't find win32gui. I'm on Windows 10.

Trying to install win32gui gives you a different error, so I tried installine pywin32 and that seems to have done the trick.

About AppNotFound except

Hi, here is my code
try:
open("netflix", throw_error=True)
except AppNotFound as e:
wb.open_new_tab('https://www.netflix.com/tw/')

I think, when netflix app is not open, it will raise some exception like AppNotFound, but it didn't work,
if I write the wrong code to use this function, please show me the right way, thanks.

IndexError: list index out of range

LOADING APPS... (JUST ONCE)
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\ACER\AppData\Local\Programs\Python\Python39\lib\threading.py", line 950, in _bootstrap_inner
self.run()
File "C:\Users\ACER\AppData\Local\Programs\Python\Python39\lib\threading.py", line 888, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\ACER\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1475, in _readerthread
buffer.append(fh.read())
File "C:\Users\ACER\AppData\Local\Programs\Python\Python39\lib\codecs.py", line 322, in decode
(result, consumed) = self.buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x94 in position 3381: invalid start byte
Traceback (most recent call last):
File "c:\Users\ACER\Documents\GitHub\Ami\dfgsdg.py", line 1, in
from AppOpener import open
File "C:\Users\ACER\AppData\Local\Programs\Python\Python39\lib\site-packages\AppOpener_init
.py", line 7, in
check.check_json()
File "C:\Users\ACER\AppData\Local\Programs\Python\Python39\lib\site-packages\AppOpener\check.py", line 63, in check_json
create_file()
File "C:\Users\ACER\AppData\Local\Programs\Python\Python39\lib\site-packages\AppOpener\check.py", line 52, in create_file
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, encoding='utf-8')
File "C:\Users\ACER\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 503, in run
stdout, stderr = process.communicate(input, timeout=timeout)
File "C:\Users\ACER\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1130, in communicate
stdout, stderr = self._communicate(input, endtime, timeout)
File "C:\Users\ACER\AppData\Local\Programs\Python\Python39\lib\subprocess.py", line 1525, in _communicate
stdout = stdout[0]
IndexError: list index out of range

CANNOT OPEN APPS INSTALLED IN CHINESE

Apps with English names can open correctly, but when I try to open apps with Chinese names, nothing is done.
I have also tried renaming the apps but to no avail and the function run(LS) does not list the app either.

Application not found

I am not able to open an application with Appopener.
It is showing Fritzing(application) not found.
It is also not showing up when i list all the application.

I am facing this issue in windows 11 but it is working properly in windows 10.

screenshots ๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡๐Ÿ‘‡
image

image

Weird character errors

Hi!

I'm a little newbie with python, so this may be something that I'm doing wrong, but here's the problem:

When running LS, the application names shows like this:

  1. S P O T I F Y C U S E R S M E R K A P P D A T A R O A M I N G S P O T I F Y S P O T I F Y E X E

And then, when executing this code:

from AppOpener import run

run("ls")

run("spotify")

it responds:

SPOTIFY NOT FOUND... TYPE (LS) for list of applications.

So for what I see, it works well, it's just messing with the characters, encoding, or something like that.

Running it from VS Code console (tried in Powershell but same error), versions are:

  • AppOpener 1.1
  • Python 3.8.10
  • Windows 10
  • Windows in spanish ( just in case has something to do with it )

Thanks for your help, if you need any more info or you know what i'm doing wrong, please tell me!

Edit: code had "spotify.exe" because tried also this way, but neither "spotify" or "spotify.exe" never worked

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.