Skip to content

Commit

Permalink
Merge pull request #1 from GabrielRF/master
Browse files Browse the repository at this point in the history
Update
  • Loading branch information
anaschwendler authored Oct 13, 2019
2 parents afe7ea2 + e3ac87c commit 9b4bbd8
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 92 deletions.
9 changes: 9 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
language: python
python:
- "3.5"
- "3.7"
install:
- pip install -r requirements.txt
script:
- pytest

42 changes: 0 additions & 42 deletions Pipfile

This file was deleted.

63 changes: 47 additions & 16 deletions apitrackingmore.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,38 @@
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')

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
Expand All @@ -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:
Expand All @@ -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') + ' <b>' + json['tracking_number'] + '</b>')
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 = '<code>' + geartrack.getcorreioscode(carrier, code) + '</code>'
except:
pass
try:
observacao = 'Código novo: <code>' + geartrack.getcorreioscode(carrier, code) + '</code>'
except:
pass
mensagem = ('Data: {}' +
'\nSituacao: <b>{}</b>' +
'\nObservação: {}'
Expand All @@ -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]))
1 change: 1 addition & 0 deletions misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from pymongo import MongoClient
from telebot import types


client = MongoClient()
db = client.rastreiobot

Expand Down
4 changes: 2 additions & 2 deletions rastreiobot.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ def cmd_pacotes(message):
else:
message = '<b>Clique para ver o histórico:</b>\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',
Expand Down Expand Up @@ -323,7 +323,7 @@ def cmd_concluidos(message):
else:
message = '<b>Pacotes concluídos nos últimos 30 dias:</b>\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',
Expand Down
37 changes: 5 additions & 32 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -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.*
5 changes: 5 additions & 0 deletions tests/test_helloworld.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import pytest

def test_dummy():
assert True

0 comments on commit 9b4bbd8

Please sign in to comment.