-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot_Inline.py
More file actions
686 lines (600 loc) · 44.6 KB
/
Copy pathbot_Inline.py
File metadata and controls
686 lines (600 loc) · 44.6 KB
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
import getInfAboutProduct
import telebot
import config
import checkCard
import sqlite3
import checkUser
import editUser
import win32file
import win32con
import time
from telebot import types
import re
import os
user_states = {}
bot = telebot.TeleBot(config.TOKEN)
bot.set_webhook()
def check_file_lock(filename):
try:
handle = win32file.CreateFile(
filename,
win32con.GENERIC_READ | win32con.GENERIC_WRITE,
0,
None,
win32con.OPEN_EXISTING,
0,
0
)
win32file.CloseHandle(handle)
return False
except Exception as e:
return True
def mainKeyboard(message):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
bottom1 = types.KeyboardButton("Главная")
bottom2 = types.KeyboardButton("Консультация")
bottom3 = types.KeyboardButton("Заказ")
markup.row(bottom1, bottom2)
markup.add(bottom3)
bot.send_message(message.chat.id, "Доступные команды:", reply_markup=markup)
@bot.message_handler(commands=['start', 'main', 'hello'])
@bot.message_handler(func=lambda message: message.text.lower() == 'главная')
def welcome(message):
# DB
conn = sqlite3.connect('shop.sql')
cur = conn.cursor()
cur.execute(
'CREATE TABLE IF NOT EXISTS users (id int auto_increment primary key, name varchar(255), tgId varchar(20) '
'unique not null, phone varchar(20), has_card integer default(0))')
conn.commit()
cur.close()
conn.close()
###
user_states[message.chat.id] = {'name': None, 'phone': None, 'tgId': None, 'card': 0, 'size': None}
sti = open('static/welcome.webp', 'rb')
bot.send_sticker(message.chat.id, sti)
bot.send_message(message.chat.id, "Добро пожаловать, {0.first_name}!\n "
"Я - <b>электронный сотрудник магазина по продаже тканей</b>, бот, созданный, чтобы помочь вам сделать заказ.".format(
message.from_user, bot.get_me()),
parse_mode='html', reply_markup=types.ReplyKeyboardRemove())
markup = types.InlineKeyboardMarkup()
btn1 = types.InlineKeyboardButton("Статус посылки", callback_data='status')
btn2 = types.InlineKeyboardButton("Сделать заказ", callback_data='order')
markup.row(btn1, btn2)
bot.send_message(message.chat.id,
"{0.first_name}, если вы хотите получить информацию по доставке вашего заказа, нажмите на <b>Статус посылки</b>.\n"
"Если хотите сделать заказ, нажмите на <b>Сделать заказ</b>".format(message.from_user,
bot.get_me()),
parse_mode='html', reply_markup=markup)
@bot.message_handler(commands=['order'])
@bot.message_handler(func=lambda message: message.text.lower() in {'заказ', 'заказать еще'})
def order(message):
user_states[message.chat.id] = {'token': None}
bot.send_message(message.chat.id, "Введите, пожалуйста, <b>артикул</b> товара\n"
"<b>Пример ввода: 875234</b>\n\n"
"Если вы забыли артикул товара, то можете перейти обратно в основной канал и посмотреть его\n"
"<b>Вот ссылка -> https://t.me/bravissimo_nn</b>", parse_mode='html',
reply_markup=types.ReplyKeyboardRemove())
bot.register_next_step_handler(message, get_token)
# Обработка индефикатора и подтверждение правильности выбора товара
def get_token(message):
if message.content_type == 'text':
user_states[message.chat.id]['token'] = message.text.strip()
if re.match('^/.*$', user_states[message.chat.id]['token']):
mainKeyboard(message)
else:
user_states[message.chat.id]['product_data'] = getInfAboutProduct.get_product_data(
user_states[message.chat.id]['token'])
# Проверка на существование
if not user_states[message.chat.id]['product_data']:
bot.send_message(message.chat.id, f'К сожалению, такого артикула не существует😢\n'
f'Попробуйте снова!')
order(message)
else:
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
bottom1 = types.KeyboardButton("Верно")
bottom2 = types.KeyboardButton("Неверно")
bottom3 = types.KeyboardButton("Консультация")
markup.row(bottom1, bottom2)
markup.add(bottom3)
bot.send_message(message.chat.id, "Проверьте, пожалуйста, что вы правильно ввели артикул\n"
"Данные по данному артикулу:")
# Отправка сообщения с данными о товаре и фотографией
file_path = os.path.join('photos',
f'{user_states[message.chat.id]['product_data'][1]}.jpg') # Путь к файлу в новой папке
img = open(f"{file_path}", 'rb')
bot.send_photo(message.chat.id, img,
caption=f'Название: {user_states[message.chat.id]['product_data'][1]}\n Цена: {user_states[message.chat.id]['product_data'][2]}\n Длина отреза: {user_states[message.chat.id]['product_data'][3]}\n Артикул: {user_states[message.chat.id]['product_data'][4]}',
reply_markup=markup)
# Проверка на правильный выбор
bot.register_next_step_handler(message, check_product)
else:
bot.send_message(message.chat.id, "Я не умею обрабатывать такие сообщения(\n"
"Введите, пожалуйста, текстом")
order(message)
def check_product(message):
if message.content_type == 'text':
if re.match('^/', message.text.strip()):
mainKeyboard(message)
elif message.text.strip() == 'Неверно':
order(message)
elif message.text.strip() == 'Верно':
get_info_user(message)
elif message.text.strip() == 'Консультация':
consult2(message)
else:
bot.send_message(message.chat.id,
"Выберите одну из кнопок: Верно или Неверно, либо выберите кнопку Консультация, чтобы перейти в чат с менеджером")
bot.register_next_step_handler(message, check_product)
else:
bot.send_message(message.chat.id, "Я не умею обрабатывать такие сообщения(\n"
"Введите, пожалуйста, текстом")
bot.register_next_step_handler(message, check_product)
def get_info_user(message):
# Register users
user_states[message.chat.id]['user_data'] = checkUser.get_user_data(message.from_user.id)
if user_states[message.chat.id]['user_data']:
user_states[message.chat.id]['waiting_for_button'] = True
markup = types.InlineKeyboardMarkup()
bottom1 = types.InlineKeyboardButton('Верно', callback_data='true_enter')
bottom2 = types.InlineKeyboardButton('Изменились', callback_data='edit_data')
markup.row(bottom1, bottom2)
user_states[message.chat.id]['name'] = user_states[message.chat.id]['user_data'][1]
user_states[message.chat.id]['phone'] = user_states[message.chat.id]['user_data'][3]
user_states[message.chat.id]['tgId'] = message.from_user.id
bot.send_message(message.chat.id, f'Вы уже были в нашем магазине, и у нас есть ваши данные😁',
reply_markup=types.ReplyKeyboardRemove())
bot.send_message(message.chat.id, f'Проверьте, пожалуйста, текущие данные на корректность:\n\n'
f'ФИО: {user_states[message.chat.id]['user_data'][1]}\n'
f'Номер мобильного телефона: {user_states[message.chat.id]['user_data'][3]}',
reply_markup=markup)
bot.register_next_step_handler(message, check_button_press)
else:
bot.send_message(message.chat.id, "Сейчас нужно вас зарегистрировать!\n"
"Введите, пожалуйста, через пробел с большой буквы свое ФИО\n"
"Пример ввода: Иванов Иван Иванович\n",
reply_markup=types.ReplyKeyboardRemove())
bot.register_next_step_handler(message, user_name)
def user_name(message):
if message.content_type == 'text':
user_states[message.chat.id]['name'] = message.text.strip()
if re.match('^/', user_states[message.chat.id]['name']):
mainKeyboard(message)
elif re.match(r'^[А-ЯЁа-яё]+\s+[А-ЯЁа-яё]+\s+[А-ЯЁа-яё]+$', user_states[message.chat.id]['name']):
# Ввод пользователя соответствует формату Фамилия Имя Отчество
bot.send_message(message.chat.id, "Введите свой номер телефона в формате:\n"
"79*********")
bot.register_next_step_handler(message, user_phone)
else:
# Ввод пользователя не соответствует формату ФИО
bot.send_message(message.chat.id, "Пожалуйста, введите свое ФИО в правильном формате.")
bot.register_next_step_handler(message, user_name)
else:
bot.send_message(message.chat.id, "Я не умею обрабатывать такие сообщения(\n"
"Пожалуйста, введите свое ФИО в правильном формате.")
bot.register_next_step_handler(message, user_name)
def user_phone(message):
if message.content_type == 'text':
user_states[message.chat.id]['phone'] = message.text.strip()
if re.match('^/', user_states[message.chat.id]['phone']):
mainKeyboard(message)
elif re.match(r'^79\d{9}$', user_states[message.chat.id]['phone']):
user_states[message.chat.id]['waiting_for_button'] = True
user_states[message.chat.id]['tgId'] = message.from_user.id
markup = types.InlineKeyboardMarkup()
bottom1 = types.InlineKeyboardButton('Верно', callback_data='true_enter')
bottom2 = types.InlineKeyboardButton('Неверно', callback_data='false_enter')
markup.row(bottom1, bottom2)
bot.send_message(message.chat.id, f'Мы закончили небольшую регистрацию🔥')
bot.send_message(message.chat.id,
f'Проверьте, пожалуйста, ваши данные на корректность:\n ФИО: {user_states[message.chat.id]['name']}\n Номер мобильного телефона: {user_states[message.chat.id]['phone']}',
reply_markup=markup)
bot.register_next_step_handler(message, check_button_press)
else:
# Неверный формат номера телефона
bot.send_message(message.chat.id,
"Пожалуйста, введите корректный номер мобильного телефона (номер должен содержать 11 цифр и начинаться на 79).")
bot.register_next_step_handler(message, user_phone)
else:
bot.send_message(message.chat.id, "Я не умею обрабатывать такие сообщения(\n"
"Пожалуйста, введите корректный номер телефона (номер должен содержать 11 цифр и начинаться на 79).")
bot.register_next_step_handler(message, user_phone)
def consult2(message):
file_path = os.path.join('photos',
f'{user_states[message.chat.id]['product_data'][1]}.jpg') # Путь к файлу в новой папке
img = open(f"{file_path}", 'rb')
# Отправка сообщения с данными о товаре и фотографией
bot.send_photo(config.manager_id, img,
caption=f'Консультация!\n'
f'Информация о заказе с артикулом - {user_states[message.chat.id]['product_data'][4]}:\n'
f'Название: {user_states[message.chat.id]['product_data'][1]}\n'
f'Цена: {user_states[message.chat.id]['product_data'][2]}\n'
f'Длина отреза: {user_states[message.chat.id]['product_data'][3]}\n\n'
f'Информация о пользователе:\n'
f'Ник пользователя - {message.from_user.username}\n')
bot.send_message(message.chat.id,
f'Перейдите по следующей ссылке, чтобы связаться с менеджером. Обязательно представьтесь и отправьте артикул своего товара, чтобы менеджер смог вас понять)\n\n'
f'<b>Переходите сюда</b> -> https://t.me/Artv1d', parse_mode='html',
reply_markup=types.ReplyKeyboardRemove())
@bot.message_handler(commands=['pochta'])
@bot.message_handler(func=lambda message: message.text.lower() == 'почта россии')
def pochta(message):
bot.send_message(message.chat.id, "Перейдите, пожалуйста, по ссылке -> https://www.pochta.ru/tracking\n"
"На сайте в поле *номер заказа* нужно ввести трек-номер вашего заказа, больше от вас ничего не потребуется)",
reply_markup=types.ReplyKeyboardRemove())
@bot.message_handler(commands=['sdek'])
@bot.message_handler(func=lambda message: message.text.lower() == 'сдэк')
def sdek(message):
bot.send_message(message.chat.id,
"Перейдите, пожалуйста, по ссылке -> https://www.cdek.ru/ru/tracking/?order_id=1550105567\n"
"На сайте в поле *номер заказа* нужно ввести трек-номер вашего заказа, больше от вас ничего не потребуется)",
reply_markup=types.ReplyKeyboardRemove())
@bot.message_handler(commands=['advice'])
@bot.message_handler(func=lambda message: message.text.lower() == 'консультация')
def consult(message):
bot.send_message(message.chat.id,
f'Перейдите по следующей ссылке, чтобы связаться с менеджером. Обязательно отправьте артикул своего товара, чтобы менеджер смог вас понять)\n\n'
f'<b>Переходите сюда</b> -> https://t.me/Artv1d', parse_mode='html',
reply_markup=types.ReplyKeyboardRemove())
@bot.message_handler(commands=['end'])
@bot.message_handler(func=lambda message: message.text.lower() == 'закончить')
def end(message):
bot.send_message(message.chat.id, f'Были рады видеть вас в нашем магазине, приходите еще😊',
reply_markup=types.ReplyKeyboardRemove())
@bot.message_handler(content_types=['photo', 'video', 'audio', 'sticker', 'emoji'])
def noneContent(message):
bot.reply_to(message, f'Извините, {message.from_user.first_name}, я не умею обрабатывать такие сообщения((')
@bot.callback_query_handler(func=lambda callback: True)
def callback_message(callback):
if callback.data == 'status':
markup10 = types.ReplyKeyboardMarkup(resize_keyboard=True)
item10 = types.KeyboardButton("Почта России")
item01 = types.KeyboardButton("СДЭК")
markup10.add(item10)
markup10.add(item01)
bot.send_message(callback.message.chat.id,
"Если ваш заказ отправлен службой доставки *Почта России*, нажмите на кнопку <b>Почта России</b>, если ваш заказ отправлен службой доставки *СДЭК*, нажмите на кнопку <b>СДЭК</b>",
parse_mode='html', reply_markup=markup10)
elif callback.data == 'order':
markup1 = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("Заказ")
markup1.add(item1)
bot.send_message(callback.message.chat.id,
"Чтобы сделать заказ, отправьте команду <b>/order</b> или нажмите на кнопку <b>Заказ</b>",
parse_mode='html', reply_markup=markup1)
elif callback.data == 'true_enter':
while check_file_lock('cards.xlsx'):
bot.send_message(config.manager_id,
f"Пожалуйста, закройте cards.xlsx, чтобы пользователь мог продолжить оформление заказа.")
bot.send_message(callback.message.chat.id,
f"Пожалуйста, подождите немного, пока идет проверка на наличие вашей карты.")
time.sleep(3)
user_states[callback.message.chat.id]['card'] = checkCard.check_card_status('cards.xlsx', user_states[
callback.message.chat.id]['phone'])
if not user_states[callback.message.chat.id]['user_data']:
# Доделать
conn = sqlite3.connect('shop.sql')
cur = conn.cursor()
cur.execute(
f"INSERT INTO users(name, tgId, phone, has_card) VALUES ('{user_states[callback.message.chat.id]['name']}', '{user_states[callback.message.chat.id]['tgId']}', '{user_states[callback.message.chat.id]['phone']}', '{user_states[callback.message.chat.id]['card']}')")
conn.commit()
cur.close()
conn.close()
else:
if user_states[callback.message.chat.id]['user_data'][4] == 2 and user_states[callback.message.chat.id][
'card'] != 1:
user_states[callback.message.chat.id]['card'] = 2
consultation(callback)
elif (user_states[callback.message.chat.id]['user_data'][4] != 1) and user_states[callback.message.chat.id][
'card'] == 1:
editUser.update_user_card(user_states[callback.message.chat.id]['card'],
user_states[callback.message.chat.id]['tgId'])
if user_states[callback.message.chat.id]['card'] == 0:
user_states[callback.message.chat.id]['waiting_for_button'] = True
markup = types.InlineKeyboardMarkup()
bottom1 = types.InlineKeyboardButton('Хочу', callback_data='create_card')
bottom2 = types.InlineKeyboardButton('Не хочу', callback_data='continue_without_card')
markup.row(bottom1, bottom2)
bot.send_message(callback.message.chat.id, f'Мы заметили, что у вас нет нашей дисконтной карты😞 '
f'Предлагаем вам создать ее, чтобы в дальнейшем приобретать наш товар по более выгодной цене)',
reply_markup=markup)
elif user_states[callback.message.chat.id]['card'] == 1:
consultation(callback)
elif callback.data == 'false_enter':
user_states[callback.message.chat.id]['waiting_for_button'] = False
markup1 = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("Заказ")
markup1.add(item1)
bot.send_message(callback.message.chat.id,
"Давайте заполним ваши данные заново. Отправьте, пожалуйста, команду <b>/order</b> или нажмите на кнопку <b>Заказ</b>",
parse_mode='html', reply_markup=markup1)
elif callback.data == 'edit_data':
markup = types.InlineKeyboardMarkup()
bottom1 = types.InlineKeyboardButton("ФИО", callback_data='edit_name')
bottom2 = types.InlineKeyboardButton("Номер", callback_data='edit_phone')
bottom3 = types.InlineKeyboardButton("Все", callback_data='edit_all')
markup.row(bottom1, bottom2)
markup.add(bottom3)
bot.send_message(callback.message.chat.id, f'Выберите, пожалуйста, какие данные поменялись🙃',
reply_markup=markup)
# user_states[callback.message.chat.id]['waiting_for_button'] = True
# bot.register_next_step_handler(callback.message, check_button_press)
elif callback.data == 'create_card':
user_states[callback.message.chat.id]['waiting_for_button'] = False
bot.send_message(callback.message.chat.id, "Введите, пожалуйста, вашу дату рождения в формате: ДД.ММ.ГГГГ\n"
"Пример ввода: 10.10.2000")
bot.register_next_step_handler(callback.message, lambda message: process_birthday_input(callback, message))
elif callback.data == 'continue_without_card':
consultation(callback)
elif callback.data == 'end_of_buy':
user_states[callback.message.chat.id]['waiting_for_button'] = False
bot.send_message(callback.message.chat.id,
f'Введите сколько товара вы хотите заказать в САНТИМЕТРАХ', parse_mode='html',
reply_markup=types.ReplyKeyboardRemove())
bot.register_next_step_handler(callback.message, end_of_work)
elif callback.data == 'advice':
user_states[callback.message.chat.id]['waiting_for_button'] = False
file_path = os.path.join('photos',
f'{user_states[callback.message.chat.id]['product_data'][1]}.jpg') # Путь к файлу в новой папке
img = open(f"{file_path}", 'rb')
# Отправка сообщения с данными о товаре и фотографией
bot.send_photo(config.manager_id, img,
caption=f'Консультация!\n'
f'Информация о заказе с артикулом - {user_states[callback.message.chat.id]['product_data'][4]}:\n'
f'Название: {user_states[callback.message.chat.id]['product_data'][1]}\n'
f'Цена: {user_states[callback.message.chat.id]['product_data'][2]}\n'
f'Длина отреза: {user_states[callback.message.chat.id]['product_data'][3]}\n\n'
f'Информация о пользователе:\n'
f'Ник пользователя - {callback.message.chat.username}\n'
f'ФИО - {user_states[callback.message.chat.id]['name']}\n'
f'Номер телефона - {user_states[callback.message.chat.id]['phone']}\n'
f'Информация о наличии карты - {"Есть карта" if user_states[callback.message.chat.id]['card'] == 1 else ("Карта создаётся" if user_states[callback.message.chat.id]['card'] == 2 else "Нет карты")}')
bot.send_message(callback.message.chat.id,
f'Перейдите по следующей ссылке, чтобы связаться с менеджером. Обязательно отправьте артикул своего товара, чтобы менеджер смог вас понять)\n\n'
f'<b>Переходите сюда</b> -> https://t.me/Artv1d', parse_mode='html',
reply_markup=types.ReplyKeyboardRemove())
elif callback.data == 'edit_name':
user_states[callback.message.chat.id]['waiting_for_button'] = False
bot.send_message(callback.message.chat.id, "Введите, пожалуйста, через пробел с большой буквы свое ФИО\n"
"Пример ввода: Иванов Иван Иванович\n",
reply_markup=types.ReplyKeyboardRemove())
bot.register_next_step_handler(callback.message, get_name)
elif callback.data == 'edit_phone':
user_states[callback.message.chat.id]['waiting_for_button'] = False
bot.send_message(callback.message.chat.id, "Введите, пожалуйста, новый номер в формате 79*********",
reply_markup=types.ReplyKeyboardRemove())
bot.register_next_step_handler(callback.message, get_phone)
elif callback.data == 'edit_all':
user_states[callback.message.chat.id]['waiting_for_button'] = False
bot.send_message(callback.message.chat.id, "Введите, пожалуйста, через пробел с большой буквы свое ФИО\n"
"Пример ввода: Иванов Иван Иванович\n",
reply_markup=types.ReplyKeyboardRemove())
bot.register_next_step_handler(callback.message, get_name_from_all)
elif callback.data == 'end':
user_states[callback.message.chat.id]['waiting_for_button'] = False
bot.send_message(callback.message.chat.id, f'Были рады видеть вас в нашем магазине, приходите еще😊',
reply_markup=types.ReplyKeyboardRemove())
bot.edit_message_text(chat_id=callback.message.chat.id, message_id=callback.message.message_id, text='Далее....',
reply_markup=None)
def process_birthday_input(callback, message):
if message.content_type == 'text':
user_states[callback.message.chat.id]['birthday'] = message.text.strip()
if re.match('^/.*$', user_states[message.chat.id]['birthday']):
mainKeyboard(message)
elif re.match(r'^(0[1-9]|1[0-9]|2[0-9]|3[0-1])\.(0[1-9]|1[0-2])\.(19[3-9][0-9]|20[01][0-9])$',
user_states[callback.message.chat.id]['birthday']):
user_states[callback.message.chat.id]['waiting_for_button'] = True
bot.register_next_step_handler(callback.message, check_button_press)
bot.send_message(config.manager_id, f'Создать дисконтную карту!\n'
f'Информация о пользователе:\n'
f'Ник пользователя - {callback.message.chat.username}\n'
f'ФИО - {user_states[callback.message.chat.id]['name']}\n'
f'Номер телефона - {user_states[callback.message.chat.id]['phone']}\n'
f'Дата рождения - {user_states[callback.message.chat.id]['birthday']}')
editUser.update_user_card(2, user_states[callback.message.chat.id]['tgId'])
user_states[callback.message.chat.id]['card'] = 2
consultation(callback)
else:
bot.send_message(callback.message.chat.id,
f'Неверный формат даты рождения. Введите дату в формате: ДД.ММ.ГГГГ\n'
f'Пример ввода: 10.10.2000')
bot.register_next_step_handler(callback.message, lambda message: process_birthday_input(callback, message))
else:
bot.send_message(message.chat.id, "Я не умею обрабатывать такие сообщения(\n"
"Пожалуйста, введите дату в формате: ДД.ММ.ГГГГ")
bot.register_next_step_handler(callback.message, lambda message: process_birthday_input(callback, message))
def end_of_work(message):
if message.content_type == 'text':
user_states[message.chat.id]['size'] = message.text.strip()
if re.match('^/.*$', user_states[message.chat.id]['size']):
mainKeyboard(message)
elif re.match(r'^[0-9]+$', user_states[message.chat.id]['size']):
user_states[message.chat.id]['price'] = (
float(user_states[message.chat.id]['product_data'][2].split(" ")[0]) *
float(int(user_states[message.chat.id]['size']) / 100))
if user_states[message.chat.id]['product_data'][3].split(" ")[1] == 'м':
user_states[message.chat.id]['size'] = str(int(user_states[message.chat.id]['size']) / 100)
if float(user_states[message.chat.id]['size']) <= float(
user_states[message.chat.id]['product_data'][3].split(" ")[0]):
file_path = os.path.join('photos',
f'{user_states[message.chat.id]['product_data'][1]}.jpg') # Путь к файлу в новой папке
img = open(f"{file_path}", 'rb')
# Отправка сообщения с данными о товаре и фотографией
bot.send_photo(config.manager_id, img,
caption=f'Принять заказ!\n'
f'Информация о заказе с артикулом - {user_states[message.chat.id]['product_data'][4]}:\n'
f'Название: {user_states[message.chat.id]['product_data'][1]}\n'
f'Сумма к оплате: {user_states[message.chat.id]['price']} ₽\n'
f'Длина отреза: {user_states[message.chat.id]['size']} {user_states[message.chat.id]['product_data'][3].split(" ")[1]}\n\n'
f'Информация о пользователе:\n'
f'Ник пользователя - {message.from_user.username}\n'
f'ФИО - {user_states[message.chat.id]['name']}\n'
f'Номер телефона - {user_states[message.chat.id]['phone']}\n'
f'Информация о наличии карты - {"Есть карта" if user_states[message.chat.id]['card'] == 1 else ("Карта создаётся" if user_states[message.chat.id]['card'] == 2 else "Нет карты")}')
del user_states[message.chat.id]['price']
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
bottom1 = types.KeyboardButton("Заказать еще")
bottom2 = types.KeyboardButton("Закончить")
markup.row(bottom1, bottom2)
bot.send_message(message.chat.id,
f'Ваш заказ зарегистрирован и отправлен менеджеру. В течение 12 рабочих часов менеджер свяжется с вами для приема оплаты',
parse_mode='html',
reply_markup=markup)
else:
if user_states[message.chat.id]['price']:
del user_states[message.chat.id]['price']
user_states[message.chat.id]['waiting_for_button'] = True
markup = types.InlineKeyboardMarkup()
bottom1 = types.InlineKeyboardButton("Ввести размер повторно", callback_data="end_of_buy")
bottom2 = types.InlineKeyboardButton("Закончить", callback_data="end")
markup.row(bottom1, bottom2)
bot.send_message(message.chat.id,
f"К сожалению, изначально на нашем складе нет такого количества товара, приносим свои извинения.\n"
f"Нажмите на кнопку - Ввести размер повторно, и введите размер меньший, чем {user_states[message.chat.id]['product_data'][3]}\n"
f"Или нажмите на кнопку - Закончить, если Вам недостаточно товара, который есть в наличии",
reply_markup=markup)
bot.register_next_step_handler(message, check_button_press)
else:
bot.send_message(message.chat.id,
"Пожалуйста, введите корректный размер ткани (он состоит ТОЛЬКО из цифр).")
bot.register_next_step_handler(message, end_of_work)
else:
bot.send_message(message.chat.id, "Я не умею обрабатывать такие сообщения(\n"
"Пожалуйста, введите корректный размер ткани (он состоит ТОЛЬКО из цифр).")
bot.register_next_step_handler(message, end_of_work)
def get_name(message):
if message.content_type == 'text':
user_states[message.chat.id]['name'] = message.text.strip()
if re.match('^/.*$', user_states[message.chat.id]['name']):
mainKeyboard(message)
elif re.match(r'^[А-ЯЁа-яё]+\s+[А-ЯЁа-яё]+\s+[А-ЯЁа-яё]+$', user_states[message.chat.id]['name']):
user_states[message.chat.id]['waiting_for_button'] = True
editUser.update_user_name(user_states[message.chat.id]['name'], message.from_user.id)
markup = types.InlineKeyboardMarkup()
bottom1 = types.InlineKeyboardButton('Верно', callback_data='true_enter')
bottom2 = types.InlineKeyboardButton('Неверно', callback_data='edit_data')
markup.row(bottom1, bottom2)
bot.send_message(message.chat.id,
f'Проверьте, пожалуйста, ваши данные на корректность:\n ФИО: {user_states[message.chat.id]['name']}\n Номер телефона: {user_states[message.chat.id]['phone']}',
reply_markup=markup)
bot.register_next_step_handler(message, check_button_press)
else:
# Ввод пользователя не соответствует формату ФИО
bot.send_message(message.chat.id, "Пожалуйста, введите ФИО в правильном формате.")
bot.register_next_step_handler(message, get_name)
else:
bot.send_message(message.chat.id, "Я не умею обрабатывать такие сообщения(\n"
"Пожалуйста, введите ФИО в правильном формате.")
bot.register_next_step_handler(message, get_name)
def get_phone(message):
if message.content_type == 'text':
user_states[message.chat.id]['phone'] = message.text.strip()
if re.match('^/.*$', user_states[message.chat.id]['phone']):
mainKeyboard(message)
elif re.match(r'^79\d{9}$',
user_states[message.chat.id]['phone']):
user_states[message.chat.id]['waiting_for_button'] = True
editUser.update_user_phone(user_states[message.chat.id]['phone'], message.from_user.id)
markup = types.InlineKeyboardMarkup()
bottom1 = types.InlineKeyboardButton('Верно', callback_data='true_enter')
bottom2 = types.InlineKeyboardButton('Неверно', callback_data='edit_data')
markup.row(bottom1, bottom2)
bot.send_message(message.chat.id,
f'Проверьте, пожалуйста, ваши данные на корректность:\n ФИО: {user_states[message.chat.id]['name']}\n Номер мобильного телефона: {user_states[message.chat.id]['phone']}',
reply_markup=markup)
bot.register_next_step_handler(message, check_button_press)
else:
# Неверный формат номера телефона
bot.send_message(message.chat.id,
"Пожалуйста, введите корректный номер мобильного телефона (номер должен состоять из 11 цифр и начинаться на 79).")
bot.register_next_step_handler(message, get_phone)
else:
bot.send_message(message.chat.id, "Я не умею обрабатывать такие сообщения(\n"
"Пожалуйста, введите корректный номер мобильного телефона (номер должен состоять из 11 цифр и начинаться на 79).")
bot.register_next_step_handler(message, get_phone)
def get_name_from_all(message):
if message.content_type == 'text':
user_states[message.chat.id]['name'] = message.text.strip()
if re.match('^/.*$', user_states[message.chat.id]['name']):
mainKeyboard(message)
elif re.match(r'^[А-ЯЁа-яё]+\s+[А-ЯЁа-яё]+\s+[А-ЯЁа-яё]+$', user_states[message.chat.id]['name']):
bot.send_message(message.chat.id,
"Введите, пожалуйста, новый номер мобильного телефона в формате 79*********")
bot.register_next_step_handler(message, get_all)
else:
# Ввод пользователя не соответствует формату ФИО
bot.send_message(message.chat.id, "Пожалуйста, введите ФИО в правильном формате.")
bot.register_next_step_handler(message, get_name_from_all)
else:
bot.send_message(message.chat.id, "Я не умею обрабатывать такие сообщения(\n"
"Пожалуйста, введите ФИО в правильном формате.")
bot.register_next_step_handler(message, get_name_from_all)
def get_all(message):
if message.content_type == 'text':
user_states[message.chat.id]['phone'] = message.text.strip()
if re.match('^/.*$', user_states[message.chat.id]['phone']):
mainKeyboard(message)
elif re.match(r'^79\d{9}$',
user_states[message.chat.id]['phone']):
user_states[message.chat.id]['waiting_for_button'] = True
editUser.update_user_all(user_states[message.chat.id]['phone'], user_states[message.chat.id]['name'],
message.from_user.id)
markup = types.InlineKeyboardMarkup()
bottom1 = types.InlineKeyboardButton('Верно', callback_data='true_enter')
bottom2 = types.InlineKeyboardButton('Неверно', callback_data='edit_data')
markup.row(bottom1, bottom2)
bot.send_message(message.chat.id,
f'Проверьте, пожалуйста, ваши данные на корректность:\n ФИО: {user_states[message.chat.id]['name']}\n Номер мобильного телефона: {user_states[message.chat.id]['phone']}',
reply_markup=markup)
bot.register_next_step_handler(message, check_button_press)
else:
# Неверный формат номера телефона
bot.send_message(message.chat.id,
"Пожалуйста, введите корректный номер мобильного телефона (номер должен состоять из 11 цифр и начинаться на 79).")
bot.register_next_step_handler(message, get_all)
else:
bot.send_message(message.chat.id, "Я не умею обрабатывать такие сообщения(\n"
"Пожалуйста, введите корректный номер телефона (номер должен состоять из 11 цифр и начинаться на 79).")
bot.register_next_step_handler(message, get_all)
def check_button_press(message):
chat_id = message.chat.id
if user_states[chat_id].get('waiting_for_button', True):
bot.send_message(chat_id, "Пожалуйста, используйте кнопки для подтверждения или изменения данных.")
bot.register_next_step_handler(message, check_button_press)
else:
return
def consultation(callback):
markup111 = types.InlineKeyboardMarkup()
bottom1 = types.InlineKeyboardButton("Консультация", callback_data='advice')
bottom2 = types.InlineKeyboardButton("Завершение", callback_data='end_of_buy')
markup111.row(bottom1, bottom2)
bot.send_message(callback.message.chat.id, "Ваши данные успешно зарегистрированы)\n"
"Нужна ли вам дополнительная консультация с нашим менеджером по поводу заказа?")
bot.send_message(callback.message.chat.id,
"Выберите <b>Завершение</b>, если консультация не нужна.\n"
"Выберите <b>Консультация</b>, если нужна", parse_mode='html', reply_markup=markup111)
@bot.message_handler()
def info(message):
if message.text.lower() == 'привет':
bot.send_message(message.chat.id, "😕")
bot.send_message(message.chat.id, "Добро пожаловать, {0.first_name}!\n "
"Я - <b>электронный сотрудник магазина по продаже тканей</b>, бот созданный чтобы помочь тебе сделать заказ.".format(
message.from_user, bot.get_me()),
parse_mode='html')
elif message.text.lower() == 'id':
bot.reply_to(message, f'ID: {message.from_user.id}')
elif message.text.lower() == 'test':
conn = sqlite3.connect('shop.sql')
cur = conn.cursor()
cur.execute('SELECT * FROM users')
products = cur.fetchall()
info = ''
for elm in products:
info += f'name: {elm[1]}, phone: {elm[3]}, id: {elm[2]}, card: {elm[4]}'
# Отправка сообщения с данными о товаре и фотографией
bot.send_message(message.chat.id, info)
cur.close()
conn.close()
else:
bot.reply_to(message, f'Извините, {message.from_user.first_name}, я не умею обрабатывать такие сообщения((')
bot.polling(none_stop=True)