-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
1698 lines (1358 loc) · 62.2 KB
/
bot.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import asyncio
import uuid
import aiogram
from aiogram import Bot, Dispatcher, executor, exceptions
from aiogram.types import InlineQueryResultArticle, InputTextMessageContent
import scripts.messages as msg
import scripts.markup as mk
from scripts.config import TOKEN, ADMINS, DEVELOPER_ID
from scripts.db_manager import UsersDbManager, ActionsDbManager
import scripts.ServiceMarketApi as api
from scripts.text_parser import get_order_text, get_item_description, stats_text
from scripts.email_sender import send_photo
bot = Bot(TOKEN)
dp = Dispatcher(bot)
# UsersDbManager.clear()
loop = asyncio.get_event_loop()
@dp.inline_handler(lambda inline_query: inline_query.query.startswith('show_by_model_'))
async def show_by_model(inline_query):
data = inline_query.query[14:]
data = data.split('|')
tel_id = inline_query.from_user.id
user = await UsersDbManager.get_user(tel_id, loop)
try:
model = data[0]
sub_category_id = int(data[1])
except Exception:
if user.language == 'ru':
text = msg.nothing_found_article_ru.format(data[0])
elif user.language == 'uk':
text = msg.nothing_found_article_ukr.format(data[0])
else:
text = msg.nothing_found_article_en.format(data[0])
result_id = str(uuid.uuid4())
message_content = InputTextMessageContent(text)
result = InlineQueryResultArticle(
id=result_id, title=text,
thumb_url='https://img.icons8.com/dotty/2x/nothing-found.png',
thumb_height=400, thumb_width=400,
input_message_content=message_content
)
await bot.answer_inline_query(inline_query.id, results=[result], cache_time=1)
return
search_results = await api.search_by_model(model, user.language)
products = []
print(search_results)
if type(search_results['data']['products']['products']) is dict:
all_items = search_results['data']['products']['products'].values()
else:
all_items = search_results['data']['products']['products']
for item in all_items:
if item['category_id'] == int(sub_category_id):
products.append(item)
if inline_query.offset != '':
offset = int(inline_query.offset)
else:
offset = 0
if len(products) < offset + 20:
next_offset = ''
end = len(products)
else:
next_offset = offset + 20
end = next_offset
results = []
for i in range(offset, end):
product = products[i]
try:
url = product['url']
stock = int(product['stock'])
price = product['price']
name = product['name']
image_url = product['image']
if stock > 20:
if user.language == 'ru':
stock = 'более 20-ти'
elif user.language == 'ukr':
stock = 'більше 20-ти'
else:
stock = 'more than 20'
result_id = str(uuid.uuid4())
item_description = await get_item_description(product, user.language, loop)
message_content = InputTextMessageContent(item_description, parse_mode='HTML')
except KeyError:
print('Key Error')
continue
if url is not None:
keyboard = mk.go_to_site_keyboard(url, user.language)
else:
keyboard = None
if user.language == 'ru':
description = 'Цена: {0} грн В наличии шт.: {1}'.format(price, stock)
elif user.language == 'uk':
description = 'Ціна: {0} грн В наявності шт.: {1}'.format(price, stock)
else:
description = 'Cost: {0} uah In stock: {1}'.format(price, stock)
results.append(
InlineQueryResultArticle(
id=result_id, title=name, description=description,
thumb_url=image_url,
thumb_height=400, thumb_width=400,
input_message_content=message_content,
reply_markup=keyboard
))
print(next_offset)
try:
await bot.answer_inline_query(inline_query.id, results=results, next_offset=str(next_offset), cache_time=1)
except aiogram.utils.exceptions.NetworkError:
print('Network error, file too large')
@dp.inline_handler(lambda inline_query: inline_query.query.startswith('show_by_article_'))
async def show_by_article(inline_query):
article = inline_query.query[16:]
tel_id = inline_query.from_user.id
user = await UsersDbManager.get_user(tel_id, loop)
products = await api.search_by_number(article, user.language)
if len(products) == 0:
if user.language == 'ru':
text = msg.nothing_found_article_ru.format(article)
elif user.language == 'uk':
text = msg.nothing_found_article_ukr.format(article)
else:
text = msg.nothing_found_article_en.format(article)
result_id = str(uuid.uuid4())
message_content = InputTextMessageContent(text)
result = InlineQueryResultArticle(
id=result_id, title=text,
thumb_url='https://img.icons8.com/dotty/2x/nothing-found.png',
thumb_height=400, thumb_width=400,
input_message_content=message_content
)
await bot.answer_inline_query(inline_query.id, results=[result], cache_time=1)
return
print('Offset ' + inline_query.offset)
if inline_query.offset != '':
offset = int(inline_query.offset)
else:
offset = 0
if len(products) < offset + 20:
next_offset = ''
end = len(products)
else:
next_offset = offset + 20
end = next_offset
results = []
for i in range(offset, end):
product = products[i]
try:
url = product['url']
stock = product['stock']
price = product['price']
name = product['name']
image_url = product['image']
if stock > 20:
if user.language == 'ru':
stock = 'более 20-ти'
elif user.language == 'ukr':
stock = 'більше 20-ти'
else:
stock = 'more than 20'
result_id = str(uuid.uuid4())
item_description = await get_item_description(product, user.language, loop)
message_content = InputTextMessageContent(item_description, parse_mode='HTML')
except KeyError:
print('Key Error')
continue
if url is not None:
keyboard = mk.go_to_site_keyboard(url, user.language)
else:
keyboard = None
if user.language == 'ru':
description = 'Цена: {0} грн В наличии шт.: {1}'.format(price, stock)
elif user.language == 'uk':
description = 'Ціна: {0} грн В наявності шт.: {1}'.format(price, stock)
else:
description = 'Cost: {0} uah In stock: {1}'.format(price, stock)
results.append(
InlineQueryResultArticle(
id=result_id, title=name, description=description,
thumb_url=image_url,
thumb_height=400, thumb_width=400,
input_message_content=message_content,
reply_markup=keyboard
))
print(next_offset)
try:
await bot.answer_inline_query(inline_query.id, results=results, next_offset=str(next_offset), cache_time=1)
except aiogram.utils.exceptions.NetworkError:
print('Network error, file too large')
@dp.inline_handler()
async def show_by_articleee(inline_query):
print(inline_query.query)
print('TEST')
@dp.message_handler(commands=['admin'])
async def admin(message):
tel_id = message.chat.id
if tel_id not in ADMINS and tel_id != DEVELOPER_ID:
await bot.send_message(tel_id, '❌ У вас нет прав администратора')
return
await bot.send_message(tel_id, 'Панель администратора', disable_notification=True, reply_markup=mk.admin_menu)
@dp.message_handler(commands=['cancel'])
async def cancel(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
await UsersDbManager.update_context(tel_id, '0', loop)
if user.language == 'ru':
text = 'Операция отменена'
elif user.language == 'uk':
text = 'Операція скасована'
else:
text = 'Operation canceled'
await bot.send_message(tel_id, text, disable_notification=True)
@dp.message_handler(commands=['start', 'contacts'])
async def start(message):
tel_id = message.chat.id
lang = message.from_user.locale
name = message.from_user.first_name
print(name)
if not await UsersDbManager.user_exist(tel_id, loop):
if lang is not 'ru' and lang is not 'uk' and lang is not 'en':
lang = 'ru'
await UsersDbManager.add_user(tel_id, '0', lang, loop)
await ActionsDbManager.add('new_user', datetime.datetime.now(), loop)
user = await UsersDbManager.get_user(tel_id, loop)
if not user.is_using:
await UsersDbManager.update_is_using(tel_id, True, loop)
await ActionsDbManager.add('user_returned', datetime.datetime.now(), loop)
if user.language == 'ru':
text = msg.greeting_ru.format(name)
keyboard = mk.main_menu_ru
elif user.language == 'uk':
text = msg.greeting_ukr.format(name)
keyboard = mk.main_menu_uk
else:
text = msg.greeting_en.format(name)
keyboard = mk.main_menu_en
await bot.send_message(tel_id, text, reply_markup=keyboard, disable_notification=True)
if message.text.startswith('/contacts'):
if user.language == 'ru':
text = msg.contacts_ru
elif user.language == 'ukr':
text = msg.contacts_ukr
else:
text = msg.contacts_en
await bot.send_message(tel_id, text, disable_notification=True, parse_mode='HTML')
@dp.message_handler(lambda message: message.text == '📩 Сделать рассылку')
async def send_message(message):
tel_id = message.chat.id
if tel_id not in ADMINS and tel_id != DEVELOPER_ID:
await bot.send_message(tel_id, '❌ У вас нет прав администратора', disable_notification=True)
return
await bot.send_message(tel_id, ('Отправьте мне сообщение, которое нужно разослать. Это может быть текст, картинка,'
' видео, стикер или файл. Если хотите отменить операцию, используйте /cancel'), disable_notification=True)
await UsersDbManager.update_context(tel_id, 'wait_for_message', loop)
@dp.message_handler(lambda message: message.text == '📊 Статистика')
async def stats(message):
tel_id = message.chat.id
if tel_id not in ADMINS and tel_id != DEVELOPER_ID:
await bot.send_message(tel_id, '❌ У вас нет прав администратора')
return
first_date = datetime.datetime.now() - datetime.timedelta(days=1)
second_date = datetime.datetime.now()
actions = await ActionsDbManager.get_actions_beside_dates(first_date, second_date, loop)
text = '''Статистика за последние сутки'''
text += stats_text(actions)
await bot.send_message(tel_id, text, disable_notification=True, reply_markup=mk.stats_keyboard())
@dp.callback_query_handler(lambda call: call.data.startswith('stats_'))
async def stats_per_days(call):
tel_id = call.message.chat.id
days = int(call.data[6:])
print('Test')
if tel_id not in ADMINS and tel_id != DEVELOPER_ID:
await bot.send_message(tel_id, '❌ У вас нет прав администратора')
return
first_date = datetime.datetime.now() - datetime.timedelta(days=days)
second_date = datetime.datetime.now()
actions = await ActionsDbManager.get_actions_beside_dates(first_date, second_date, loop)
if days == 1:
text = '''Статистика за последние сутки'''
elif days == 7:
text = '''Статистика за последнюю неделю'''
elif days == 30:
text = '''Статистика за последний месяц'''
text += stats_text(actions)
try:
await bot.edit_message_text(text, tel_id, message_id=call.message.message_id, reply_markup=mk.stats_keyboard())
except exceptions.MessageNotModified:
print('Message is not modified')
@dp.message_handler(lambda message: UsersDbManager.sync_get_context(message.chat.id) == 'wait_for_message',
content_types=['text', 'photo', 'video', 'sticker', 'document'])
async def wait_for_message(message):
tel_id = message.chat.id
await UsersDbManager.update_context(tel_id, '0', loop)
message_counter = 0
audience_lost = 0
audience_returned = 0
all_users = await UsersDbManager.get_all_users(loop)
if message.text is not None:
content = message.text
for user in all_users:
try:
await bot.send_message(user.tel_id, content, parse_mode='HTML')
if not user.is_using:
audience_returned += 1
await UsersDbManager.update_is_using(user.tel_id, True, loop)
await ActionsDbManager.add('user_returned', datetime.datetime.now(), loop)
message_counter += 1
except Exception:
print('User not found')
if user.is_using:
audience_lost+=1
await ActionsDbManager.add('user_lost', datetime.datetime.now(), loop)
await UsersDbManager.update_is_using(user.tel_id, False, loop)
elif message.sticker is not None:
sticker_file_id = message.sticker.file_id
for user in all_users:
try:
await bot.send_sticker(user.tel_id, sticker_file_id)
if not user.is_using:
audience_returned += 1
await ActionsDbManager.add('user_returned', datetime.datetime.now(), loop)
await UsersDbManager.update_is_using(user.tel_id, True, loop)
except Exception:
print('User not found')
if user.is_using:
audience_lost += 1
await ActionsDbManager.add('user_lost', datetime.datetime.now(), loop)
await UsersDbManager.update_is_using(user.tel_id, False, loop)
elif message.photo is []:
photo_file_id = message.photo[0].file_id
for user in all_users:
try:
await bot.send_photo(user.tel_id, photo_file_id)
if not user.is_using:
audience_returned += 1
await ActionsDbManager.add('user_returned', datetime.datetime.now(), loop)
await UsersDbManager.update_is_using(user.tel_id, True, loop)
except Exception:
print('User not found')
if user.is_using:
audience_lost += 1
await ActionsDbManager.add('user_lost', datetime.datetime.now(), loop)
await UsersDbManager.update_is_using(user.tel_id, False, loop)
elif message.video is not None:
video_file_id = message.video.file_id
for user in all_users:
try:
await bot.send_video(user.tel_id, video_file_id)
if not user.is_using:
audience_returned += 1
await ActionsDbManager.add('user_returned', datetime.datetime.now(), loop)
await UsersDbManager.update_is_using(user.tel_id, True, loop)
except Exception:
print('User not found')
if user.is_using:
audience_lost += 1
await ActionsDbManager.add('user_lost', datetime.datetime.now(), loop)
await UsersDbManager.update_is_using(user.tel_id, False, loop)
elif message.document is not None:
file_id = message.document.file_id
for user in all_users:
try:
await bot.send_document(user.tel_id, file_id)
if not user.is_using:
audience_returned += 1
await ActionsDbManager.add('user_returned', datetime.datetime.now(), loop)
await UsersDbManager.update_is_using(user.tel_id, True, loop)
except Exception:
print('User not found')
if user.is_using:
audience_lost += 1
await ActionsDbManager.add('user_lost', datetime.datetime.now(), loop)
await UsersDbManager.update_is_using(user.tel_id, False, loop)
text = '''✅ Рассылка закончена
📩 {0} сообщений успешно доставлено
'''.format(message_counter)
if audience_lost > 0:
text += '''👤 {0} человек отписалось от бота и не получили сообщение'''.format(audience_lost)
if audience_returned > 0:
text += '''🚶♂️ {0} человек вернулись в бот'''.format(audience_returned)
await bot.send_message(tel_id, text, disable_notification=True)
@dp.message_handler(lambda message: message.text == '⬅️ Назад' or
message.text == '⬅️ Назад' or
message.text == '⬅️ Back')
async def to_main_menu(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
keyboard = mk.main_menu_ru
text = 'Главное меню'
elif user.language == 'uk':
keyboard = mk.main_menu_uk
text = 'Головне меню'
else:
keyboard = mk.main_menu_en
text = 'Main menu'
await UsersDbManager.update_context(tel_id, '0', loop)
await bot.send_message(tel_id, text, reply_markup=keyboard, disable_notification=True)
'''
Language change
'''
@dp.message_handler(lambda message: message.text == 'Сменить язык 🇷🇺' or
message.text == 'Змінити мову 🇺🇦' or
message.text == 'Change language 🇬🇧')
async def change_language(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
text = 'Выберите язык'
elif user.language == 'uk':
text = 'Виберіть мову'
else:
text = 'Choose language'
keyboard = mk.language_keyboard
await bot.send_message(tel_id, text, reply_markup=keyboard, disable_notification=True)
@dp.message_handler(lambda message: message.text == 'Русский 🇷🇺' or
message.text == 'Українська 🇺🇦' or
message.text == 'English 🇬🇧')
async def choose_language(message):
tel_id = message.chat.id
if message.text == 'Русский 🇷🇺':
new_lang = 'ru'
await bot.send_message(tel_id, 'Язык изменен', reply_markup=mk.main_menu_ru, disable_notification=True)
elif message.text == 'Українська 🇺🇦':
new_lang = 'uk'
await bot.send_message(tel_id, 'Мова змінена', reply_markup=mk.main_menu_uk, disable_notification=True)
elif message.text == 'English 🇬🇧':
new_lang = 'en'
await bot.send_message(tel_id, 'Language changed', reply_markup=mk.main_menu_en, disable_notification=True)
await UsersDbManager.update_language(tel_id, new_lang, loop)
'''
FAQ
'''
@dp.message_handler(lambda message: message.text == '🖊 Вопросы и ответы' or
message.text == '🖊 Питання і відповіді' or
message.text == '🖊 FAQ')
async def faq(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
keyboard = mk.faq_keyboard_ru
elif user.language == 'uk':
keyboard = mk.faq_keyboard_ukr
else:
keyboard = mk.faq_keyboard_en
await bot.send_message(tel_id, message.text, disable_notification=True, reply_markup=keyboard)
@dp.message_handler(lambda message: message.text == 'Контакты' or
message.text == 'Контакти' or
message.text == 'Contacts')
async def contacts(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
text = msg.contacts_ru
elif user.language == 'uk':
text = msg.contacts_ukr
else:
text = msg.contacts_en
await bot.send_message(tel_id, text, disable_notification=True, parse_mode='HTML')
@dp.message_handler(lambda message: message.text == 'Где найти модель техники?' or
message.text == 'Де знайти модель техніки?' or
message.text == 'Where I can find model number')
async def where_model(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
text = msg.where_model_ru
elif user.language == 'uk':
text = msg.where_model_ukr
else:
text = msg.where_model_en
await bot.send_message(tel_id, text, disable_notification=True, parse_mode='MARKDOWN')
@dp.message_handler(lambda message: message.text == 'Какие способы доставки?' or
message.text == 'Які є способі доставки?' or
message.text == 'Delivery')
async def what_delivery(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
text = msg.delivery_method_ru
elif user.language == 'uk':
text = msg.delivery_method_ukr
else:
text = msg.delivery_method_en
await bot.send_message(tel_id, text, disable_notification=True, parse_mode='HTML')
@dp.message_handler(lambda message: message.text == 'Какие способы оплаты?' or
message.text == 'Які є способи оплати?' or
message.text == 'Payment')
async def what_payments(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
text = msg.payment_method_ru
elif user.language == 'uk':
text = msg.payment_method_ukr
else:
text = msg.payment_method_en
await bot.send_message(tel_id, text, disable_notification=True, parse_mode='HTML')
@dp.message_handler(lambda message: message.text == 'Как стать оптовым клиентом?' or
message.text == 'Як стати оптовим клієнтом?' or
message.text == 'How to become a wholesale customer?')
async def how_can_opt(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
text = msg.how_can_opt_ru
elif user.language == 'uk':
text = msg.how_can_opt_ukr
else:
text = msg.how_can_opt_en
await bot.send_message(tel_id, text, disable_notification=True, parse_mode='MARKDOWN')
@dp.message_handler(lambda message: message.text == 'Как вернуть или поменять товар?' or
message.text == 'Як повернути або замінити товар?' or
message.text == 'How to return or exchange an item?')
async def how_change(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
text = msg.how_exchange_ru
elif user.language == 'uk':
text = msg.how_exchange_ukr
else:
text = msg.how_exchange_en
await bot.send_message(tel_id, text, disable_notification=True, parse_mode='MARKDOWN')
'''
Check order status
'''
@dp.message_handler(lambda message: message.text == '🚚 Проверить статус заказа' or
message.text == '🚚 Статус замовлення' or
message.text == '🚚 Check order status')
async def check_order_status(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
keyboard = mk.get_order_method(user.language)
await bot.delete_message(tel_id, message.message_id)
await bot.send_message(tel_id, message.text, reply_markup=keyboard, disable_notification=True)
@dp.callback_query_handler(lambda call: call.data == 'orders_by_number')
async def order_by_number(call):
tel_id = call.message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
text = 'Введите номер заказа'
elif user.language == 'uk':
text = 'Введіть номер замовлення'
else:
text = 'Please enter order number'
await bot.send_message(tel_id, text, disable_notification=True)
await UsersDbManager.update_context(tel_id, 'wait_order_number', loop)
@dp.message_handler(lambda message: UsersDbManager.sync_get_context(message.chat.id) == 'wait_order_number')
async def wait_order_number(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if message.text is None or any(c.isalpha() for c in message.text):
if user.language == 'ru':
text = msg.incorrect_ru
elif user.language == 'uk':
text = msg.incorrect_ukr
else:
text = msg.incorrect_en
await bot.send_message(tel_id, text, disable_notification=True)
return
order = await api.search_by_order(message.text, user.language)
if order == []:
if user.language == 'ru':
text = msg.nothing_found_ru.format(message.text)
elif user.language == 'uk':
text = msg.nothing_found_ukr.format(message.text)
else:
text = msg.nothing_found_en.format(message.text)
await bot.send_message(tel_id, text, disable_notification=True, parse_mode='HTML')
return
text = get_order_text(message.text, order, user.language)
await bot.send_message(tel_id, text, disable_notification=True, parse_mode='MARKDOWN')
await UsersDbManager.update_context(tel_id, '0', loop)
@dp.callback_query_handler(lambda call: call.data == 'orders_by_phone')
async def order_by_phone(call):
tel_id = call.message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.phone == '0':
if user.language == 'ru':
text = msg.enter_mobile_ru
keyboard = mk.share_contact_ru
elif user.language == 'uk':
text = msg.enter_mobile_ukr
keyboard = mk.share_contact_ukr
else:
text = msg.enter_mobile_en
keyboard = mk.share_contact_en
await bot.send_message(tel_id, text, reply_markup=keyboard, disable_notification=True)
await UsersDbManager.update_context(tel_id, 'wait_new_phone', loop)
return
keyboard = mk.get_yes_no_phone(user.language)
if user.language == 'ru':
text = msg.this_is_your_number_ru
elif user.language == 'uk':
text = msg.this_is_your_number_ukr
else:
text = msg.this_is_your_number_en
try:
await bot.edit_message_text(text.format(user.phone), tel_id, call.message.message_id, reply_markup=keyboard)
except exceptions.MessageNotModified:
print('Message is not modified')
@dp.callback_query_handler(lambda call: call.data == 'change_number')
async def order_by_phone(call):
tel_id = call.message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
text = msg.enter_new_mobile_ru
keyboard = mk.share_contact_ru
elif user.language == 'uk':
text = msg.enter_new_mobile_ukr
keyboard = mk.share_contact_ukr
else:
text = msg.enter_new_mobile_en
keyboard = mk.share_contact_en
await bot.send_message(tel_id, text, disable_notification=True, reply_markup=keyboard)
await UsersDbManager.update_context(tel_id, 'wait_new_phone', loop)
@dp.message_handler(lambda message: UsersDbManager.sync_get_context(message.chat.id) == 'wait_new_phone',
content_types=['contact', 'text'])
async def wait_new_phone(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if (message.text is None or len(message.text) < 10 or any(c.isalpha() for c in message.text)) and message.contact is None:
if user.language == 'ru':
text = msg.incorrect_ru
elif user.language == 'uk':
text = msg.incorrect_ukr
else:
text = msg.incorrect_en
await bot.send_message(tel_id, text, disable_notification=True)
return
if message.contact is not None:
phone = message.contact.phone_number
else:
phone = message.text
await UsersDbManager.update_phone(tel_id, phone, loop)
await UsersDbManager.update_context(tel_id, '0', loop)
orders = await api.search_orders_by_phone(phone, user.language)
if orders == []:
if user.language == 'ru':
text = msg.nothing_found_by_number_ru.format(phone)
keyboard = mk.main_menu_ru
elif user.language == 'uk':
text = msg.nothing_found_by_number_ukr.format(phone)
keyboard = mk.main_menu_uk
else:
text = msg.nothing_found_by_number_en.format(phone)
keyboard = mk.main_menu_en
await bot.send_message(tel_id, text, disable_notification=True, reply_markup=keyboard)
return
keyboard = mk.orders_by_phone(orders, user.phone, user.language)
if user.language == 'ru':
text = 'Ваши заказы'
elif user.language == 'uk':
text = 'Ваші замовлення'
else:
text = 'Your orders'
await bot.send_message(tel_id, text, reply_markup=keyboard, disable_notification=True)
@dp.callback_query_handler(lambda call: call.data == 'my_phone')
async def my_phone(call):
tel_id = call.message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
orders = await api.search_orders_by_phone(user.phone, user.language)
if orders == []:
if user.language == 'ru':
text = msg.nothing_found_by_number_ru.format(user.phone)
elif user.language == 'uk':
text = msg.nothing_found_by_number_ukr.format(user.phone)
else:
text = msg.nothing_found_by_number_en.format(user.phone)
await bot.send_message(tel_id, text, disable_notification=True)
return
keyboard = mk.orders_by_phone(orders, user.phone, user.language)
if user.language == 'ru':
text = 'Ваши заказы'
elif user.language == 'uk':
text = 'Ваші замовлення'
else:
text = 'Your orders'
try:
await bot.edit_message_text(text, tel_id, call.message.message_id, reply_markup=keyboard)
except exceptions.MessageNotModified:
print('Message is not modified')
@dp.callback_query_handler(lambda call: call.data.startswith('more_orders_'))
async def more_orders(call):
tel_id = call.message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
data = call.data[12:]
data = data.split('|')
phone = data[0]
current_pos = int(data[1])
orders = await api.search_orders_by_phone(phone, user.language)
keyboard = mk.orders_by_phone(orders, phone, user.language, current_pos)
if user.language == 'ru':
text = 'Ваши заказы'
elif user.language == 'uk':
text = 'Ваші замовлення'
else:
text = 'Your orders'
try:
await bot.edit_message_text(text, tel_id, call.message.message_id, reply_markup=keyboard)
except exceptions.MessageNotModified:
print('Message is not modified')
@dp.callback_query_handler(lambda call: call.data.startswith('order_'))
async def order_show(call):
tel_id = call.message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
order_num = call.data[6:]
order = await api.search_by_order(order_num, user.language)
if order == []:
if user.language == 'ru':
text = msg.nothing_found_ru.format(order_num)
elif user.language == 'uk':
text = msg.nothing_found_ukr.format(order_num)
else:
text = msg.nothing_found_en.format(order_num)
await bot.send_message(tel_id, text, disable_notification=True, parse_mode='HTML')
return
text = get_order_text(order_num, order, user.language)
keyboard = mk.back_to_orders(user.language)
try:
await bot.edit_message_text(text, tel_id, call.message.message_id, reply_markup=keyboard, parse_mode='MARKDOWN')
except exceptions.MessageNotModified:
print("Message is not modified")
@dp.callback_query_handler(lambda call: call.data == 'back_to_orders')
async def back_to_orders(call):
await my_phone(call)
'''
Search
'''
@dp.message_handler(lambda message: message.text == '🔎 Найти деталь' or
message.text == '🔎 Знайти деталь' or
message.text == '🔎 Find spare part')
async def find_detail(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
keyboard = mk.find_detail_keyboard_ru
elif user.language == 'uk':
keyboard = mk.find_detail_keyboard_ukr
else:
keyboard = mk.find_detail_keyboard_en
await bot.send_message(tel_id, message.text, disable_notification=True, reply_markup=keyboard)
@dp.message_handler(lambda message: message.text == 'Найти по названию' or
message.text == 'Знайти за назвою' or
message.text == 'Search by name')
async def search_by_name(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
text = msg.enter_name_ru
elif user.language == 'uk':
text = msg.enter_namw_ukr
else:
text = msg.enter_name_en
await bot.send_message(tel_id, text, disable_notification=True)
await UsersDbManager.update_context(tel_id, 'wait_for_article', loop)
@dp.message_handler(lambda message: message.text == 'Поиск по фото (пересылка менеджеру)' or
message.text == 'Пошук по фото (пересилання менеджеру)' or
message.text == 'Photo search (send to manager)')
async def search_by_photo(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
text = msg.enter_mobile_ru
keyboard = mk.share_contact_ru
elif user.language == 'uk':
text = msg.enter_mobile_ukr
keyboard = mk.share_contact_ukr
else:
text = msg.enter_mobile_en
keyboard = mk.share_contact_en
await bot.send_message(tel_id, text, disable_notification=True, reply_markup=keyboard)
await UsersDbManager.update_context(tel_id, 'wait_phone_photo', loop)
@dp.message_handler(lambda message: message.text == 'Поиск по модели' or
message.text == 'Пошук по моделі' or
message.text == 'Search by model')
async def search_by_model(message):
tel_id = message.chat.id
user = await UsersDbManager.get_user(tel_id, loop)
if user.language == 'ru':
text = msg.enter_model_name_ru
elif user.language == 'uk':
text = msg.enter_model_name_ukr
else:
text = msg.enter_model_name_en
await bot.send_message(tel_id, text, disable_notification=True)
await UsersDbManager.update_context(tel_id, 'wait_model_name', loop)
@dp.message_handler(lambda message: message.text == 'Знайти по артикулу' or
message.text == 'Найти по артикулу' or
message.text == 'Find by stock number')
async def find_by_article(message):