Wi-Fi and VPN script

Hi, I tried to create a script that
1 - Checks if Wi-Fi is connected
2 - If not checks available SSIDs
3 - Connects to a specific SSID if available
4 - Connects to a specific VPN

Here's the code:

on VPNSETUP()
launch application "System Events"
delay 0.2
tell application "System Events"
tell process "NetShade"
tell menu bar 2
ignoring application responses
click menu bar item 1
end ignoring
end tell
end tell
end tell
do shell script "killall System\ Events"
delay 0.1
tell application "System Events"
tell process "NetShade"
tell menu 1 of menu bar item 1 of menu bar 2
if exists menu item "Disconnect" then
click menu item "Disconnect"
else
click menu item "Connect"
tell menu "Connect" of menu item "Connect"
click menu item "Canada 1 (ca1)"
end tell
end if
end tell
end tell
end tell
set endresult to "win"
end VPNSETUP

on CONNECTION()
do shell script "networksetup -setairportnetwork en0 SSIDNAME2"
repeat with i from 1 to 2
try
do shell script "ping -o -t 2 www.google.com"
exit repeat
on error
if i = 2 then
do shell script "networksetup -setairportnetwork en0 SSIDNAME1"
repeat with i from 1 to 2
try
do shell script "ping -o -t 2 www.google.com"
exit repeat
on error
if i = 2 then
error number -128
else
VPNSETUP()
end if
end try
end repeat
else
VPNSETUP()
end if
end try
end repeat
end CONNECTION

set SSID to do shell script "/System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport -I | awk '/ SSID: / {print $2}'"
if SSID is "" then
set results to paragraphs 2 thru -1 of ( do shell script "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport -s | sed -nE 's/[ ](.) [a-z0-9]{2}:[a-z0-9]{2}:.+/\1/p'")
if (results contains "SSIDNAME2") or (results contains "SSIDNAME1") then
CONNECTION()
else
display dialog "Done"
end if
else
display dialog "Done"
end if

(the two "display dialog" are there just as a test to see if everything works as intended)

Now I'm sure this doesn't look neat at all (I know just some basic Python so any suggestion will be profoundly appreciated) but the problem is another one:
If I choose to run it as a script by assigning it to a Touchbar button it works smoothly, whereas if I try to run it as an app it returns various errors such as missing directories, inability to get the "connect" menu item, etc. The only difference between the codes is that in the app one I added a loop (on idle) so that I just have to start it once.

Imprint | Privacy Policy