-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
412 lines (281 loc) · 13 KB
/
main.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
from aiogram import Bot, Dispatcher, executor, types
from aiogram.dispatcher.filters import Command,Text
from aiogram.types import Message,ReplyKeyboardRemove
import aiohttp
import keyboards
from status import TEST
import config
from aiogram.dispatcher import FSMContext
from aiogram.contrib.fsm_storage.memory import MemoryStorage
import func
import sqlite as sql
import time
import asyncio
PROXY_URL ='http://104.227.97.168:8000'
STOP=True
PROXY_AUTH = aiohttp.BasicAuth(login='qY5bWs', password='kjMHoV')
FIRST_POST={'title':'','url':'','price':'','img':''}
storage = MemoryStorage()
bot = Bot(token=config.API_TOKEN, proxy=PROXY_URL, proxy_auth=PROXY_AUTH)
#bot = Bot(token=config.API_TOKEN)
dp = Dispatcher(bot,storage=storage)
async def replace_link(link:str):
st=link
if link.startswith('https://m.avito.ru'):
st=link.replace('https://m.avito.ru','https://www.avito.ru')
elif link.startswith('http://m.avito.ru'):
st=link.replace('http://m.avito.ru','https://www.avito.ru')
elif link.startswith('m.avito.ru'):
st=link.replace('m.avito.ru','https://www.avito.ru')
elif link.startswith('www.avito.ru'):
st=link.replace('www.avito.ru','https://www.avito.ru')
return st
async def write_link(message: types.Message,state:FSMContext):
global STOP
if message.text == 'Назад':
await state.finish()
await message.reply(config.WELCOM_TEXT, reply_markup=keyboards.main_menu)
else:
link_tp=str(message.text).strip()
link=await replace_link(link_tp)
tstap=func.check_link(link)
if tstap!=None:
async with state.proxy() as data:
data['Q1'] = link
try:
flag=False
if sql.select_users_check_user_time(message.chat.id):
if sql.update_user_link(message.chat.id,link,tstap):
flag=True
STOP=True
else:
if sql.add_users_user(message.chat.id,link,0,24,tstap):
flag = True
if flag==True:
await message.reply(config.WRITE_LINK_TEXT, reply_markup=keyboards.main_menu)
await state.finish()
else:
await message.reply(config.BAD_ADD_LINK, reply_markup=keyboards.back_menu)
except:
await message.reply(config.BAD_ADD_LINK, reply_markup=keyboards.back_menu)
else:
print('неправильная ссылка')
await message.reply(config.BAD_LINK_TEXT, reply_markup=keyboards.back_menu)
async def write_time(message: types.Message,state:FSMContext):
if message.text == 'Назад':
await state.finish()
await message.reply(config.WELCOM_TEXT, reply_markup=keyboards.main_menu)
else:
kt=func.check_time(message.text)
if kt!=None:
async with state.proxy() as data:
data['Q2'] = str(message.text).strip()
if sql.update_user_time(message.chat.id,kt[0],kt[1]):
await message.reply(config.WRITE_TIME_TEXT, reply_markup=keyboards.main_menu)
await state.finish()
else:
await message.reply(config.BAD_WRITE_TIME_TEXT, reply_markup=keyboards.back_menu)
else:
print('неправильное время')
await message.reply(config.BAD_WRITE_TIME_TEXT, reply_markup=keyboards.back_menu)
async def send_welcom(message: types.Message):
await message.reply(config.WELCOM_TEXT, reply_markup=keyboards.main_menu)
async def send_back_welcom(message: types.Message):
await message.reply(config.BACK_TEXT, reply_markup=keyboards.main_menu)
async def send_help(message: types.Message):
await message.reply(config.HELP_TEXT, reply_markup=keyboards.main_menu)
async def send_settings(message: types.Message):
await message.reply(config.SETTINGS_TEXT, reply_markup=keyboards.settings_menu)
async def send_add_link(message: types.Message):
await message.reply(config.ADD_LINK_TEXT, reply_markup=keyboards.back_menu)
await TEST.Q1.set()
async def send_set_time(message: types.Message):
await message.reply(config.ADD_TIME_TEXT, reply_markup=keyboards.set_time_menu)
async def send_set_time_2(message: types.Message,state=None):
await message.reply(config.SET_TIME_TEXT, reply_markup=keyboards.back_menu)
await TEST.Q2.set()
@dp.message_handler(state=TEST.Q2)
async def answer_time(message:types.Message,state:FSMContext):
answer=message.text
await write_time(message,state)
@dp.message_handler(state=TEST.Q1)
async def answer_link(message:types.Message,state:FSMContext):
answer=message.text
await write_link(message,state)
@dp.message_handler(Command("help"),state=None)
async def send_welcome(message: types.Message):
await send_help(message)
@dp.message_handler(Text(equals=["Назад"]))
async def send_back_text(message: types.Message):
await send_back_welcom(message)
@dp.message_handler(Text(equals=["Помощь"]))
async def send_help_text(message: types.Message):
await send_help(message)
@dp.message_handler(Text(equals=["Настройки"]))
async def send_settings_text(message: types.Message):
await send_settings(message)
@dp.message_handler(Text(equals=["Добавить ссылку"]))
async def send_add_link_text(message: types.Message):
await send_add_link(message)
@dp.message_handler(Text(equals=["Настройка времени"]))
async def send_set_time_text(message: types.Message):
await send_set_time(message)
@dp.message_handler(Text(equals=["Установить время"]))
async def send_set_time_text_2(message: types.Message):
await send_set_time_2(message)
@dp.message_handler(Text(equals=["Управление"]))
async def send_conntrol_menu(message: types.Message):
try:
res = sql.select_users_user_all(message.chat.id)
print(res)
if res != None:
vk = 'Мониторин выключен'
if res[6] == 1:
vk = 'Мониторинг включен'
st = vk + '\nВаши настройки:\nВремя: от ' + str(res[3]) + ' до ' + str(res[4]) + '\n' + 'Ссылка: ' + str(
res[2]) + '\n\n'
await message.reply(st, reply_markup=keyboards.main_menu_control)
else:
await send_welcom(message)
except:
await send_welcom(message)
#await message.reply(config.CONTOL_MONITOR_TEXT, reply_markup=keyboards.main_menu_control)
@dp.message_handler(Text(equals=["Старт"]))
async def start_monitor(message: types.Message):
global STOP
STOP=False
try:
res=sql.select_users_user_all(message.chat.id)
if res!=None:
vk='Мониторин выключен'
if str(res[2])!='':
if sql.update_vk(message.chat.id,1):
await message.reply(config.START_MONITOR_TEXT, reply_markup=keyboards.main_menu)
else:
await message.reply(config.NO_LINK_TEXT, reply_markup=keyboards.main_menu)
else:
await message.reply(config.NO_LINK_TEXT, reply_markup=keyboards.main_menu)
except:
pass
@dp.message_handler(Text(equals=["Стоп"]))
async def stop_monitor(message: types.Message):
global STOP
STOP=True
try:
res = sql.select_users_user_all(message.chat.id)
if res != None:
vk = 'Мониторин включен'
if str(res[2]) != '':
if sql.update_vk(message.chat.id, 0):
await message.reply(config.STOP_MONITOR_TEXT, reply_markup=keyboards.main_menu)
else:
await message.reply(config.NO_LINK_TEXT, reply_markup=keyboards.main_menu)
except:
pass
@dp.message_handler(Command("start"),state=None)
async def send_welcome_text(message: types.Message):
global STOP
STOP = False
try:
res=sql.select_users_user_all(message.chat.id)
print(res)
if res!=None:
vk='Мониторин выключен'
if res[6]==1:
vk='Мониторинг включен'
st=vk+'\nВаши настройки:\nВремя: от '+str(res[3])+' до '+str(res[4])+'\n'+'Ссылка: '+str(res[2])+'\n\n'
await message.reply(st, reply_markup=keyboards.main_menu)
else:
await send_welcom(message)
except:
await send_welcom(message)
async def start_parser():
global FIRST_POST
global STOP
base_last=set()
posts=[]
new_date=0
x=0
try:
print('проверка заданий в базе')
res = sql.select_users_for_pars()
if res!=None:
for mas in res:
try:
print('выполняем задания')
link=mas[2]
date_last=mas[5]
chat_id=mas[1]
new_date=0
base_last = str(mas[7]).split(',')
base = func.get_link(link)
print('записей в базе ')
if base != None:
bb=func.soup_parsing(base,base_id_items=base_last)
b_items = bb[0]
ss_last=','.join(bb[1])
if b_items != None:
if len(b_items) > 0:
print('записей в b_items ')
for m in b_items:
try:
date1 = func.str_to_date(m['time'])
tm = date1
print('проверяем дату')
if tm > date_last:
if tm>new_date:
new_date=tm
FL = True
FIRST_POST['title'] = m['title']
FIRST_POST['url'] = m['url']
FIRST_POST['price'] = m['price']
FIRST_POST['img'] = m['img']
if FIRST_POST['title'] == '' or FIRST_POST['url'] == '' or FIRST_POST[
'price'] == '' or FIRST_POST['img'] == '':
FL = False
if FL == True:
sent = '<a href="{}">{}</a> \n\nцена: {}'.format(FIRST_POST['url'],
FIRST_POST['title'],
FIRST_POST['price'])
posts.append({'chat_id':chat_id,'img':FIRST_POST['img'],'post':sent})
except:
continue
pflag=False
if len(posts)>0:
print('переходим к постингу')
for cap in posts:
if STOP==False:
try:
time.sleep(1)
chat_id=cap['chat_id']
img=cap['img']
post=cap['post']
await bot.send_photo(chat_id,img,post,parse_mode='HTML')
if pflag==False:
if sql.update_last_pars(chat_id,new_date,ss_last):
pflag=True
except:
print('error post')
continue
print('выполнен постинг')
else:
print('нет постов для постинга')
else:
print('no new obv')
else:
print('empty base')
except:
print('error p')
continue
else:
print('no tasks')
return None
except:
return None
async def parsing(wait_for):
while True:
await asyncio.sleep(wait_for)
await start_parser()
if __name__ == '__main__':
dp.loop.create_task(parsing(config.TIME_PARSING))
executor.start_polling(dp, skip_updates=True)