Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed correios api #163

Merged
merged 2 commits into from
Jul 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apis/apicorreios.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,10 @@ def format_object(data):
message = f'Data: {data}\nLocal: {local}'
if situacao: message = f'{message}\nSituação: {situacao}'
if observacao: message = f'{message}\nObservação: {observacao}'
try:
message = f"{message}\n{evento['comentario']}"
except KeyError:
pass
stats.append(message)
return stats

Expand Down
24 changes: 21 additions & 3 deletions rastreio/providers/correios.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import hashlib
from datetime import datetime
from datetime import timedelta
from typing import Optional, Union
Expand Down Expand Up @@ -37,6 +38,9 @@ def add_emojis(text):
'Pagamento confirmado': '💸',
'Objeto apreendido por órgão de fiscalização': '👮',
'Objeto dispensado do pagamento de impostos': '🎉',
'A entrada do objeto no Brasil não foi autorizada pelos órgãos fiscalizadores': '❌',
'Objeto está em rota de entrega': '🚚',
'Objeto será entregue em instantes': '🏎',
}
if casos.get(text):
return f'{text} {casos.get(text)}'
Expand All @@ -60,6 +64,8 @@ def get_local(unidade):


def format_object(data):
if 'SRO-031' in str(data):
return status.NOT_FOUND
if 'SRO-020' in str(data['objetos'][0]):
return status.NOT_FOUND
stats = []
Expand Down Expand Up @@ -88,6 +94,12 @@ def format_object(data):
message = f'<i>Data</i>: {date}\n<i>Local</i>: {local}'
if situacao: message = f'{message}\n<i>Situação</i>: <b>{situacao}</b>'
if observacao: message = f'{message}\n<i>Destino</i>: {observacao}'
try:
link = evento["comentario"]
if 'http' in link:
message = f'{message}\n<a href="{link}">Clique aqui para rastrear a entrega📍</a>'
except:
pass
stats.append(message)
return stats

Expand Down Expand Up @@ -115,18 +127,21 @@ def should_update_app_token(self) -> bool:

async def get_app_token(self, session: aiohttp.ClientSession) -> str:
if self.should_update_app_token():
date = datetime.now().strftime('%d/%m/%Y %H:%M:%S')
sign = hashlib.md5(f'requestToken{self.token}data{date}'.encode()).hexdigest()
headers = {
"content-type": "application/json",
"user-agent": "Dart/2.18 (dart:io)",
}

body = {
"requestToken": self.token
"requestToken": self.token,
"data":f"{date}","sign":f"{sign}"
}

try:
response = await session.post(
url="https://proxyapp.correios.com.br/v1/app-validation",
url="https://proxyapp.correios.com.br/v2/app-validation",
headers=headers,
json=body,
)
Expand All @@ -150,7 +165,9 @@ async def request(self, url: str, session: aiohttp.ClientSession, retries=MAX_RE
try:
response = await session.get(url, headers=headers)
response.raise_for_status()
except (aiohttp.ClientResponseError, aiohttp.ClientConnectorError) as e:
except aiohttp.client_exceptions.ClientResponseError:
return 'SRO-031'
except:# (aiohttp.ClientResponseError, aiohttp.ClientConnectorError) as e:
if retries > 0:
seconds = (MAX_REQUEST_RETRIES - retries + 1) * 5
await asyncio.sleep(seconds)
Expand All @@ -164,6 +181,7 @@ async def request(self, url: str, session: aiohttp.ClientSession, retries=MAX_RE
async def _request_get_code(self, code: str, session: aiohttp.ClientSession) -> dict:
url = f"https://proxyapp.correios.com.br/v1/sro-rastro/{code}"
data = await self.request(url, session)
# print(data)
try:
return code, format_object(data)
except:
Expand Down
2 changes: 1 addition & 1 deletion rastreio/workers/clean_packages.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def run(dry_run):
if (
any(status in latest_status for status in final_status)
and time_diff > int_del
or time_diff > 2 * int_del
or time_diff > 4 * int_del
):
if not dry_run:
db.delete_package(elem['code'])
Expand Down
16 changes: 15 additions & 1 deletion rastreiobot.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ def send_status_sorted(bot, chatid, case, status):
16: '<b>Recebido no Brasil</b> 🇧🇷',
17: '<b>Carteiro não atendido</b> 🚪',
18: '<b>Objeto não chegou à unidade</b>',
19: '<b>Recebido na unidade de distribuição</b>',
}
if status:
send_clean_msg(bot, chatid, cases.get(case) + status)
Expand Down Expand Up @@ -145,6 +146,7 @@ def list_by_status(chatid):
received_br = get_packages_by_status('Correios do Brasil', cursor, chatid)
not_answered = get_packages_by_status('arteiro não atendido', cursor, chatid)
not_arrived = get_packages_by_status('Objeto ainda não chegou à unidade', cursor, chatid)
dist_unit = get_packages_by_status('Objeto recebido na unidade de distribuição', cursor, chatid)
try:
send_status_sorted(bot, chatid, 1, waiting_payment)
send_status_sorted(bot, chatid, 2, payed)
Expand All @@ -164,6 +166,7 @@ def list_by_status(chatid):
send_status_sorted(bot, chatid, 16, received_br)
send_status_sorted(bot, chatid, 17, not_answered)
send_status_sorted(bot, chatid, 18, not_arrived)
send_status_sorted(bot, chatid, 19, dist_unit)
except Exception:
bot.send_message('9083329', 'Erro MongoBD.')
qtd = -1
Expand Down Expand Up @@ -221,7 +224,10 @@ def add_package(code, user):
'''
code = code.upper()
print("add_package")
stat = get_update(code)
try:
stat = get_update(code)
except:
stat = status.NOT_FOUND
if stat in [status.OFFLINE, status.TYPO]:
return stat
else:
Expand Down Expand Up @@ -593,6 +599,14 @@ def cmd_cadastro_mercado_livre(message):
bot.reply_to(message, url)


@bot.message_handler(content_types=['pinned_message'])
def on_pin(message):
if message.chat.id > 0:
try:
bot.delete_message(message.from_user.id, message.message_id)
except:
pass

@bot.message_handler(func=lambda m: True)
def cmd_magic(message):
'''
Expand Down
4 changes: 2 additions & 2 deletions utils/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ def check_type(code):

if CORREIOS_RE.search(str(code)):
return Correios
elif ALI_RE.search(str(code)):
return trackingmore
# elif ALI_RE.search(str(code)):
# return trackingmore
else:
return None

Expand Down
Loading