diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..d9b31de --- /dev/null +++ b/.travis.yml @@ -0,0 +1,9 @@ +language: python +python: + - "3.5" + - "3.7" +install: + - pip install -r requirements.txt +script: + - pytest + diff --git a/Pipfile b/Pipfile deleted file mode 100644 index f880aae..0000000 --- a/Pipfile +++ /dev/null @@ -1,42 +0,0 @@ -[[source]] -url = "https://pypi.python.org/simple" -verify_ssl = true -name = "pypi" - -[packages] -appdirs = "==1.4.0" -backports-abc = "==0.5" -"beautifulsoup4" = "==4.5.3" -bokeh = "==0.12.4" -"bs4" = "==0.0.1" -decorator = "==4.0.11" -ipdb = "==0.10.2" -ipython = "==5.2.1" -ipython-genutils = "==0.1.0" -"jinja2" = "==2.9.5" -markupsafe = "==0.23" -numpy = "==1.12.0" -pandas = "==0.19.2" -pexpect = "==4.2.1" -pickleshare = "==0.7.4" -prompt-toolkit = "==1.0.13" -ptyprocess = "==0.5.1" -pygments = "==2.2.0" -pymongo = "==3.4.0" -pyparsing = "==2.1.10" -pytelegrambotapi = "==2.3.0" -python-dateutil = "==2.6.0" -pytz = "==2016.10" -pyyaml = "==3.12" -requests = "*" -simplegeneric = "==0.8.1" -six = "==1.10.0" -tornado = "==4.4.2" -traitlets = "==4.3.1" -wcwidth = "==0.1.7" -var-dump = "*" - -[dev-packages] - -[requires] -python_version = "3.6" diff --git a/apitrackingmore.py b/apitrackingmore.py index 98af956..9e76469 100644 --- a/apitrackingmore.py +++ b/apitrackingmore.py @@ -3,10 +3,11 @@ import trackingmore import sys from datetime import datetime +from pymongo import ASCENDING, MongoClient import apigeartrack as geartrack -# https://www.trackingmore.com/api-index.html +# https://www.trackingmore.com/api-index.html - Codigos de retorno da API config = configparser.ConfigParser() config.sections() config.read('bot.conf') @@ -14,14 +15,26 @@ key = config['TRACKINGMORE']['key'] trackingmore.set_api_key(key) +client = MongoClient() +db = client.rastreiobot + +def set_carrier_db(code, carrier): + db.rastreiobot.update_one({ + "code": code.upper()}, { + "$set": { + "carrier": carrier + } + }) + def get_or_create_tracking_item(carrier, code): + try: - tracking_data = trackingmore.create_tracking_data(carrier, code) - trackingmore.create_tracking_item(tracking_data) tracking_data = trackingmore.get_tracking_item(carrier, code) except trackingmore.trackingmore.TrackingMoreAPIException as e: - if e.err_code == 4016: # Already exists + if e.err_code == 4031 or e.err_code == 4017: + tracking_data = trackingmore.create_tracking_data(carrier, code) + trackingmore.create_tracking_item(tracking_data) tracking_data = trackingmore.get_tracking_item(carrier, code) else: raise e @@ -30,12 +43,21 @@ def get_or_create_tracking_item(carrier, code): def get_carriers(code): + package = db.rastreiobot.find_one({ + "code": code + }) + + if package: + carriers = package['carrier'] + return carriers if isinstance(carriers, list) else [carriers] + carriers = trackingmore.detect_carrier_from_code(code) carriers.sort(key=lambda carrier: carrier['code']) + set_carrier_db(code, carriers) return carriers -def get(code, *args, **kwargs): +def get(code, retries=0): try: carriers = get_carriers(code) except trackingmore.trackingmore.TrackingMoreAPIException as e: @@ -51,31 +73,39 @@ def get(code, *args, **kwargs): elif e.err_code == 4031: response_status = status.NOT_FOUND_TM else: - print(carrier, tracking_data) if not tracking_data or 'status' not in tracking_data: response_status = status.OFFLINE elif tracking_data['status'] == 'notfound': response_status = status.NOT_FOUND_TM elif len(tracking_data) >= 10: - return formato_obj(tracking_data, carrier, code) + set_carrier_db(code, carrier) + return formato_obj(tracking_data, carrier, code, retries) return response_status -def formato_obj(json, carrier, code): +def formato_obj(json, carrier, code, retries): stats = [] stats.append(str(u'\U0001F4EE') + ' ' + json['tracking_number'] + '') - tabela = json['origin_info']['trackinfo'] + try: + tabela = json['origin_info']['trackinfo'] + except KeyError: + if retries < 0: + return get(sys.argv[1], retries-1) + else: + return status.NOT_FOUND_TM mensagem = '' for evento in reversed(tabela): - data = datetime.strptime(evento['Date'], '%Y-%m-%d %H:%M:%S').strftime("%d/%m/%Y %H:%M") + try: + data = datetime.strptime(evento['Date'], '%Y-%m-%d %H:%M:%S').strftime("%d/%m/%Y %H:%M") + except ValueError: + data = datetime.strptime(evento['Date'], '%Y-%m-%d %H:%M').strftime("%d/%m/%Y %H:%M") situacao = evento['StatusDescription'] observacao = evento['checkpoint_status'] - if 'Import clearance success' in situacao: - try: - observacao = '' + geartrack.getcorreioscode(carrier, code) + '' - except: - pass + try: + observacao = 'Código novo: ' + geartrack.getcorreioscode(carrier, code) + '' + except: + pass mensagem = ('Data: {}' + '\nSituacao: {}' + '\nObservação: {}' @@ -85,5 +115,6 @@ def formato_obj(json, carrier, code): if __name__ == '__main__': - print(get(sys.argv[1], 0)) + print(get(sys.argv[1], retries=3)) #get(sys.argv[1], 0) + #print(get_carriers(sys.argv[1])) diff --git a/misc.py b/misc.py index 8625e9a..69e41b0 100644 --- a/misc.py +++ b/misc.py @@ -4,6 +4,7 @@ from pymongo import MongoClient from telebot import types + client = MongoClient() db = client.rastreiobot diff --git a/rastreiobot.py b/rastreiobot.py index 7da0a40..0fc2565 100644 --- a/rastreiobot.py +++ b/rastreiobot.py @@ -275,7 +275,7 @@ def cmd_pacotes(message): else: message = 'Clique para ver o histórico:\n' + message msg_split = message.split('\n') - for elem in range(0, len(msg_split), 10): + for elem in range(0, len(msg_split)-1, 10): s = '\n' bot.send_message(chatid, s.join(msg_split[elem:elem+10]), parse_mode='HTML', @@ -323,7 +323,7 @@ def cmd_concluidos(message): else: message = 'Pacotes concluídos nos últimos 30 dias:\n' + message msg_split = message.split('\n') - for elem in range(0, len(msg_split), 10): + for elem in range(0, len(msg_split)-1, 10): s = '\n' bot.send_message(chatid, s.join(msg_split[elem:elem+10]), parse_mode='HTML', diff --git a/requirements.txt b/requirements.txt index cbb6275..3ab3b5c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,32 +1,5 @@ -appdirs==1.4.0 -backports-abc==0.5 -beautifulsoup4==4.5.3 -bokeh==0.12.4 -bs4==0.0.1 -decorator==4.0.11 -ipdb==0.10.2 -ipython==5.2.1 -ipython-genutils==0.1.0 -Jinja2==2.9.5 -MarkupSafe==0.23 -numpy==1.12.0 -packaging==16.8 -pandas==0.19.2 -pexpect==4.2.1 -pickleshare==0.7.4 -prompt-toolkit==1.0.13 -ptyprocess==0.5.1 -Pygments==2.2.0 -pymongo==3.4.0 -pyparsing==2.1.10 -pyTelegramBotAPI==3.6.6 -python-dateutil==2.6.0 -pytz==2016.10 -PyYAML==3.13 -requests==2.20.0 -simplegeneric==0.8.1 -six==1.10.0 -tornado==4.4.2 -traitlets==4.3.1 -wcwidth==0.1.7 -sentry-sdk==0.7.14 +beautifulsoup4==4.* +pymongo==3.* +pytest==5.* +requests==2.* +sentry-sdk==0.* diff --git a/tests/test_helloworld.py b/tests/test_helloworld.py new file mode 100644 index 0000000..5aa475c --- /dev/null +++ b/tests/test_helloworld.py @@ -0,0 +1,5 @@ +import pytest + +def test_dummy(): + assert True +