📜 ⬆️ ⬇️

Automatic notification of changes in the status of postal parcels via SMS

Recently, I began to do a lot of shopping in online stores, and I often find myself finding myself very often checking the status of my packages (it’s impossible to worry with our mail).
The search for ready-made solutions led only to paid services. As a result, it was decided to figure out something of their own.
Under the cut list of services used and detailed instructions.

Choice of auxiliary services


The next step of the search was devoted to services that provide the ability to periodically run various scripts in the absence of (oh, what a nuisance) personal server. The choice fell on Google Apps Script . The Javascript is a modification that is familiar to me.
SMS.ru was chosen as the SMS gateway, which provides the ability to send an unlimited number of free standard length SMS (180 Latin characters, 60 Unicode) to a personal phone number.
The tracking function was decided to borrow from [I don’t know how] the universal Chinese service 17track .

If your operator has an email2sms gate, you can skip all references to SMS.ru.
')

Cooking


Before starting to write ... code, we need:


I need to paint the registration process in detail, I hope.

API ID for SMS.ru can be obtained here: online.sms.ru/?panel=settings&subpanel=api


To create a script in Google Apps Script it is required, oddly enough, to go to the site of this service .
There the following window will meet us (if it has not been disabled earlier):

We need an "Empty Project".

Hash for 17track does not have to be received, the generation is now done by Google Apps Script. The ready-made code for insertion into the script can be obtained here .

All the necessary ingredients are obtained, you can proceed to the code.

Code


var user = ["%API ID%", "%TELNO%"]; var num = [ ["%TRACKCODE1%", "%NAME1%"], ["%TRACKCODE2%", "%NAME2%"], ... ["%TRACKCODEn%", "%NAMEn%"], ]; var errors = { "hsErr": "Wrong hash", "unAllow": "You've changed parameter \"lo\" in query URL. Set it to \"www.17track.net\"", "hsNon": "There's no hash" } var success = false; function sendSMS(text){ UrlFetchApp.fetch("http://sms.ru/sms/send?api_id="+user[0]+"&to="+user[1]+"&text="+encodeURI(text)); } function digest2str(digest){ var str = ''; var i = 0; for (i=0; i<digest.length; i++) { byte = digest[i]; if (byte < 0) byte += 256; byteStr = byte.toString(16); // Ensure we have 2 chars in our byte, pad with 0 if (byteStr.length == 1) byteStr = '0'+byteStr; str += byteStr; } return str; } function checkStatus(){ var i = 0; for(i=0; i<num.length; i++){ var response = UrlFetchApp.fetch("http://www.17track.net/r/handlertrack.ashx?callback=&num="+num[i][0]+"&pt=0&cm=0&cc=0&_="+Math.random()); UserProperties.setProperty("q", response.getContentText()); var result = Utilities.jsonParse(response.getContentText()); var sendstring = num[i][1]+": "; if(result["ret"] == 1){ if(result["dat"]["f"] == "0"){ sendstring += "Track code not found"; }else{ success = true; } }else{ sendstring += errors[result["msg"]] ? errors[result["msg"]] : "Please, leave comment on habrahabr, error message: "+result["msg"]; } if(success){ if(UserProperties.getProperty(num[i][0]) != result["dat"]["z"]["b"]){ translit = UrlFetchApp.fetch("http://translate.google.com/translate_a/t?client=t&q="+encodeURI(result["dat"]["z"]["b"])); translitobj = Utilities.jsonParse(translit.getContentText()); if(translitobj[0][0][3]){ for(z in translitobj[0]){ sendstring += translitobj[0][z][3]+" "; } }else{ sendstring += result["dat"]["z"]["b"]; } sendSMS(sendstring); UserProperties.setProperty(num[i][0], result["dat"]["z"]["b"]); success = false; } }else{ sendSMS(sendstring); } } } 

You can also not mess with sms.ru, if your operator has email2sms-gate. For example, instructions for Megaphone Udmurtia . If there is, you can find it on the operator’s website by searching for the word “e-mail”. Removed transliteration (if someone doesn’t know how to glue messages on a gate, please let me know if I’m transliterated). The code name is added to the subject of the message.
Code
 var user = [ "%EMAIL1%", "%EMAIL2%", ... "%EMAILn%" ]; var num = [ ["%TRACKCODE1%", "%NAME1%"], ["%TRACKCODE2%", "%NAME2%"], ... ["%TRACKCODEn%", "%NAMEn%"], ]; var errors = { "hsErr": "Wrong hash", "unAllow": "You've changed parameter \"lo\" in query URL. Set it to \"www.17track.net\"", "hsNon": "There's no hash" } var success = false; function sendSMS(code, text){ var i = 0; for(i=0; i<user.length; i++){ MailApp.sendEmail(user[i], code, text); } } function digest2str(digest){ var str = ''; var i = 0; for (i=0; i<digest.length; i++) { byte = digest[i]; if (byte < 0) byte += 256; byteStr = byte.toString(16); if (byteStr.length == 1) byteStr = '0'+byteStr; str += byteStr; } return str; } function checkStatus(){ var i = 0; for(i=0; i<num.length; i++){ hashstr = num[i][0]+"{EDFCE98B-1CE6-4D87-8C4A-870D140B62BA}0{EDFCE98B-1CE6-4D87-8C4A-870D140B62BA}www.17track.net"; dig = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, hashstr); hs = digest2str(dig); var response = UrlFetchApp.fetch("http://s1.17track.net/Rest/HandlerTrackPost.ashx?lo=www.17track.net&num="+num[i][0]+"&hs="+hs); UserProperties.setProperty("q", response.getContentText()); var result = Utilities.jsonParse(response.getContentText().replace(/^\((.*)\)$/, "$1")); var code = num[i][1] var sendstring = ""; if(result["ret"] == 1){ if(result["dat"]["f"] == "0"){ sendstring += "Track code not found"; }else{ success = true; } }else{ sendstring += errors[result["msg"]] ? errors[result["msg"]] : "Please, leave comment on habrahabr, error message: "+result["msg"]; } if(success){ if(UserProperties.getProperty(num[i][0]) != result["dat"]["z"]["b"]){ sendstring += result["dat"]["z"]["b"]; sendSMS(code, sendstring); UserProperties.setProperty(num[i][0], result["dat"]["z"]["b"]); success = false; } }else{ sendSMS(code, sendstring); } } } 


I will only make a reservation that, as a flag, there was an alert for this status or not, the date of the last status is used, which is saved in User Properties and compared each time.

In the code it remains to substitute the API ID, phone number and tracking number / hash pairs. Now you need to configure the periodic execution of this script. To do this, go to "Resources-> Triggers of the current project", click "Add a trigger" and customize the image and likeness (interval, you can choose your own):


The result will be such messages on the mobile phone when it detects a change in status:


Questions and suggestions with alternatives, corrections and optimizations are accepted.

PS: I thank the unknown (or did I just not find it?) For the provided invite.

UPD:
  1. Functional changes: added assignment of their names to packages (displayed instead of track codes) and catching errors (only two errors are known, if the error is unknown, its code will come in SMS, report it here to me in a personal or via skype / twitter, ID in the profile ).
  2. "Internal" changes : processing the response of the service is made as normal JSON, not with the crutch RegExp.

If you change the ol parameter from the request to “17track.net” (instead of “ www.17track.net ”), for some reason an error occurs about the hash. They are strange, these are Chinese.
It turned out that the domain hash is also used when generating the hash.

UPD2:
My script broke, because our (Russian) mail suddenly began to produce results in Russian (recently wrote only in English, EMS writes status in Russian (as a result, does not fit into one message). Now transliteration takes place using Google Translate (again illegal use of resources)

UPD3:
Now we have a page for generating ready-made code for insertion into the script. All thanks z0rg .

UPD4:
Hash generation is done by script

UPD5:
If the status is Latin, Google Translate gave an empty string with transliteration. fix.

UPD6:
If the track code does not exist or has not yet been registered, the script fell with an error and the message did not come. fix.
Thanks for the error message - = INFINITY = - from w3bsit3-dns.com

UPD7:
A more graceful verification of the code for existence, verification of the novelty of the status according to its text (sometimes the date is not given, thanks to Dudka ), correction of problems with transliteration (if there are several sentences in the text, it turned out to take only the first one, thanks to the mail of Belarus and kakawajazz ).

UPD8:
E-mail notification version (including email @ sms gates)

UPD9:
I fixed the script to work with the updated 17track, thanks to rocket for pointing.

Source: https://habr.com/ru/post/186568/


All Articles