-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathasync_trackingmore.py
182 lines (154 loc) · 5.1 KB
/
async_trackingmore.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import configparser
import logging.handlers
import sys
from datetime import datetime
from time import time, sleep
from utils.misc import check_update
from utils.misc import async_check_update
from utils.misc import check_type
import apis.apicorreios as correios
import apis.apitrackingmore as trackingmore
import random
import requests
import telebot
import asyncio
import motor.motor_asyncio
from aiogram import Bot, Dispatcher, executor, types
from aiogram.utils import executor
config = configparser.ConfigParser()
config.read('bot.conf')
TOKEN = config['RASTREIOBOT']['TOKEN']
LOG_ALERTS_FILE = config['RASTREIOBOT']['alerts_log']
PATREON = config['RASTREIOBOT']['patreon']
INTERVAL = 0.03
logger_info = logging.getLogger('InfoLogger')
handler_info = logging.handlers.TimedRotatingFileHandler(
LOG_ALERTS_FILE, when='midnight', interval=1, backupCount=7, encoding='utf-8'
)
#handler_info = logging.FileHandler(LOG_ALERTS_FILE)
logger_info.setLevel(logging.DEBUG)
logger_info.addHandler(handler_info)
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
client = motor.motor_asyncio.AsyncIOMotorClient()
db = client.rastreiobot
async def get_package(code):
print(code)
stat = await async_check_update(code)
if stat == 0:
stat = 'Sistema dos Correios fora do ar.'
elif stat == 1:
stat = None
elif stat == 3:
stat = None
else:
cursor = await db.rastreiobot.update_one (
{ "code" : code.upper() },
{
"$set": {
"stat" : stat,
"time" : str(time())
}
})
stat = 10
return stat
def check_system():
try:
URL = ('http://webservice.correios.com.br/')
response = requests.get(URL, timeout=10)
except:
logger_info.info(str(datetime.now()) + '\tCorreios indisponível')
return False
if '200' in str(response):
return True
else:
logger_info.info(str(datetime.now()) + '\tCorreios indisponível')
return False
async def up_package(elem):
code = elem['code']
rand = random.randint(0,4)
try:
old_state = elem['stat'][len(elem['stat'])-1]
len_old_state = len(elem['stat'])
except:
old_state = ""
len_old_state = 1
if 'objeto entregue ao' in old_state.lower() and not rand:
return
elif 'objeto apreendido por órgão de fiscalização' in old_state.lower() and not rand:
return
elif 'objeto devolvido' in old_state.lower() and not rand:
return
elif 'objeto roubado' in old_state.lower() and not rand:
return
elif 'delivered' in old_state.lower() and not rand:
return
stat = await get_package(code)
if stat == 0:
return
cursor2 = await db.rastreiobot.find_one(
{
"code": code
})
try:
len_new_state = len(cursor2['stat'])
except:
len_new_state = 1
if len_old_state == len_new_state:
return
len_diff = len_new_state - len_old_state
for user in elem.get('users', []):
logger_info.info(str(datetime.now()) + ' '
+ str(code) + ' \t' + str(user) + ' \t'
+ str(len_old_state) + '\t'
+ str(len_new_state) + '\t' + str(len_diff))
try:
try:
#pacote chines com codigo br
message = (str(u'\U0001F4EE') + '<b>' + code + '</b> (' + elem['code_br'] + ')\n')
except:
message = (str(u'\U0001F4EE') + '<a href="https://t.me/rastreiobot?start=' + code + '">' + code + '</a>\n')
try:
if code not in elem[user]:
message = message + '<b>' + elem[user] + '</b>\n'
except:
pass
for k in reversed(range(1,len_diff+1)):
message = (
message + '\n'
+ cursor2['stat'][len(cursor2['stat'])-k] + '\n')
if 'objeto entregue' in message.lower() and user not in PATREON:
message = (message + '\n'
+ str(u'\U0001F4B3')
+ ' Me ajude a manter o projeto vivo!\nEnvie /doar e veja as opções '
+ str(u'\U0001F4B5'))
#if len_old_state < len_new_state:
# await bot.send_message(str(user), message, parse_mode='HTML',
# disable_web_page_preview=True)
except Exception as e:
logger_info.info(str(datetime.now())
+ ' EXCEPT: ' + str(user) + ' ' + code + ' ' + str(e))
continue
async def async_main():
cursor1 = db.rastreiobot.find()
start = time()
if check_system():
pass
else:
print("exit")
return
# await bot.send_message(str(-340600919), "oi", parse_mode='HTML',
# disable_web_page_preview=True)
tasks = []
n = 0
async for elem in cursor1:
api_type = check_type(elem['code'])
if api_type is trackingmore:
n += 1
tasks.append(up_package(elem))
await asyncio.gather(*tasks)
if __name__ == '__main__':
executor.start(dp, async_main())
# ida ao banco
# chamada da api
# fala com o usuario