Last active
July 16, 2018 07:46
-
-
Save wodim/bc2aef90b078a81ebc975ebbe69a5fea to your computer and use it in GitHub Desktop.
Get an email every time your Cainiao-tracked package moves
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# usage: python track.py <tracking no> [description] | |
import json | |
import sys | |
from dateutil.parser import parse as date_parse | |
import requests | |
MAILGUN_KEY = '' | |
MAILGUN_DOMAIN = '' | |
MAILGUN_FROM = '' | |
MAILGUN_TO = '' | |
def send_email(subject, text): | |
url = ('https://api.mailgun.net/v3/%s/messages' % MAILGUN_DOMAIN) | |
auth = ('api', MAILGUN_KEY) | |
data = {'from': 'Cainiao Tracker <%s>' % MAILGUN_FROM, 'to': [MAILGUN_TO], | |
'subject': subject, 'text': text} | |
return requests.post(url, auth=auth, data=data) | |
def state_to_string(state): | |
text, date = state | |
return '%s\n %s' % (date, text) | |
if len(sys.argv) < 2: | |
raise Exception('not enough parameters...') | |
tracking_no = sys.argv[1] | |
url = 'https://geartrack.pt/api/cainiao?id=%s' % (sys.argv[1]) | |
filename = '%s.log' % tracking_no.lower() | |
with requests.Session() as s: | |
r = s.get(url) | |
j = json.loads(r.text) | |
if 'states' not in j: | |
print('Error: %s' % j['error']) | |
sys.exit(1) | |
if not j['states']: | |
sys.exit(0) | |
states = [(x['state'], date_parse(x['date'])) for x in j['states']] | |
states = sorted(states, key=lambda state: state[1], reverse=True) | |
current_text, current_date = states[0] | |
current_ts = int(current_date.timestamp()) | |
try: | |
with open(filename) as fp: | |
last_ts = int(fp.read()) | |
except: | |
last_ts = 0 | |
if last_ts < current_ts: | |
full_history = [state_to_string(x) for x in states] | |
try: | |
title = 'New state for "%s": %s' % (sys.argv[2], current_text) | |
except IndexError: | |
title = 'New state for %s: %s' % (tracking_no, current_text) | |
body = 'History for %s:\n\n%s' % (tracking_no, '\n\n'.join(full_history)) | |
send_email(title, body) | |
with open(filename, 'wt') as fp: | |
fp.write(str(current_ts)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment