Бот на Telebot , при использовании бота одновременно двумя пользователями и более данные перемешиваются и неверно записываются в БД
Суть такая , бот для бара , при бронировании столов от двух пользователей одновременно данные первого уходят в бронь второго и наоборот . Как исправить проблему ?
import telebot
import sqlite3
import re
import datetime
import os
import requests
import time
from telebot import types
def dbconnect() :
global db , cursor
db = sqlite3.connect('data_base.db', check_same_thread=False)
cursor = db.cursor()
def tabledbconnect() :
global tbd , tbdcursor
tbd = sqlite3.connect('table_base.db', check_same_thread=False)
tbdcursor = tbd.cursor()
def db_add(user_id : int , user_name : str) :
cursor.execute('INSERT INTO Users (username, user_id , admin , phone_number) VALUES (?, ?, ?, ?)' , (user_name , user_id , 0 , 0))
db.commit()
def update_table_info(id) :
tables.clear()
data = tbdcursor.execute('SELECT * FROM Tables WHERE table_id = ?' , (id,)).fetchone()
for res in data :
tables.append(res)
def update_info(id) :
user.clear()
data = cursor.execute('SELECT * FROM Users WHERE user_id = ?' , (id,)).fetchone()
for res in data :
user.append(res)
bot = telebot.TeleBot('PRIVATE_TOKEN')
admin_id = PRIVARE_ID
user = []
tables = []
global check
check = 0
global text_spam
text_spam = ""
global table_id
global buffer_table
buffer_table = 0
markup = types.InlineKeyboardMarkup(row_width=2)
table = types.InlineKeyboardButton("?Забронировать стол" , callback_data = 'table')
help = types.InlineKeyboardButton("?️Помощь" , callback_data = 'help')
profile = types.InlineKeyboardButton("??Профиль" , callback_data= 'profile')
markup.add(table , help , profile)
table_image_path = r'tables_photo.jpg'
spam_image_path = r'spam_photo.jpg'
admin_markup = types.InlineKeyboardMarkup(row_width=2)
admin_del_reserv = types.InlineKeyboardButton("?️Удалить бронь" , callback_data='admin_del_reserv')
admin_check_reserv = types.InlineKeyboardButton("?Активные брони" , callback_data='admin_check_reserv')
admin_back = types.InlineKeyboardButton("?Назад" , callback_data='admin_back')
admin_update_tables_photo = types.InlineKeyboardButton("?️Обновить фото столов" , callback_data='admin_update_tables_photo')
admin_start_spam = types.InlineKeyboardButton("?Запустить рассылку" , callback_data='admin_start_spam')
admin_edit_spam = types.InlineKeyboardButton("✏️Изменить текст и картинку рассылки" , callback_data='admin_edit_spam')
admin_markup.add(admin_del_reserv , admin_check_reserv , admin_update_tables_photo , admin_edit_spam , admin_start_spam)
@bot.message_handler(commands=['start'])
def welcome(message) :
global buffer_table, table_reserv
dbconnect()
tabledbconnect()
cursor.execute('''
CREATE TABLE IF NOT EXISTS Users (
user_id INTEGER NOT NULL,
username TEXT NOT NULL,
admin INTEGER NULL,
phone_number VARCHAR(50) NULL
)
''')
db.commit()
tbdcursor.execute('''
CREATE TABLE IF NOT EXISTS Tables (
table_id INTEGER NOT NULL,
reservation INTEGER NULL,
phone_number VARCHAR(50) NULL,
name TEXT NULL,
user_id INTEGER NULL,
time VARCHAR(50) NULL,
persons INTEGER NULL,
min_persons INTEGER NULL,
max_persons INTEGER NULL
)
''')
tbd.commit()
table_id = tbdcursor.execute('SELECT table_id FROM Tables').fetchall()
global user_id_reservation
user_id_reservation = tbdcursor.execute('SELECT user_id FROM Tables').fetchall()
user_id = cursor.execute('SELECT user_id FROM Users').fetchall()
user_id_reservation = str(user_id_reservation).replace("(" , "")
user_id_reservation = str(user_id_reservation).replace(")" , "")
user_id_reservation = str(user_id_reservation).replace("," , "")
if [item for item in user_id if message.chat.id in item] :
bot.send_message(message.chat.id , f'✅Вы есть в нашей базе данных!')
update_info(message.chat.id)
else :
bot.send_message(message.chat.id , f'✅Вы добавлены в нашу базу данных!')
db_add(message.chat.id , message.from_user.first_name)
update_info(message.chat.id)
if str(message.chat.id) in user_id_reservation :
table_id_selected = tbdcursor.execute('SELECT table_id FROM Tables WHERE user_id = ?', (message.chat.id,)).fetchone()
table_id_selected = str(table_id_selected).replace("(" , "")
table_id_selected = str(table_id_selected).replace(")" , "")
table_id_selected = str(table_id_selected).replace("," , "")
update_table_info(table_id_selected)
bot.send_message(message.chat.id , f'??Здравствуйте , {message.from_user.first_name} Вас приветствует NehaBarKST , у вас забронирован столик пол номером {tables[0]}')
buffer_table = 1
else :
buffer_table = 0
bot.send_message(message.chat.id , f'??Здравствуйте , {message.from_user.first_name} Вас приветствует NehaBarKST')
if user[2] == 1 :
bot.send_message(message.chat.id , "Пожалуйста выберите действие:" , reply_markup=admin_markup)
else : bot.send_message(message.chat.id , "Пожалуйста выберите действие:" , reply_markup=markup)
jls_extract_var = bot
@jls_extract_var.callback_query_handler(func=lambda call:True)
def answer(call) :
global check
global buffer_table
tabledbconnect()
table_id = tbdcursor.execute('SELECT table_id FROM Tables').fetchall()
user_id_reservation = tbdcursor.execute('SELECT user_id FROM Tables').fetchall()
user_id = cursor.execute('SELECT user_id FROM Users').fetchall()
user_id_reservation = str(user_id_reservation).replace("(" , "")
user_id_reservation = str(user_id_reservation).replace(")" , "")
user_id_reservation = str(user_id_reservation).replace("," , "")
if call.data == "table" :
pattern = r'^\+?[0-9]{11,12}$'
match = re.search(pattern, user[3])
if match :
bot.delete_message(call.message.chat.id , call.message.message_id)
if str(call.message.chat.id) in user_id_reservation :
bot.send_message(call.message.chat.id , f'?Вы уже забронировали стол! \nПроверьте бронь в профиле' , reply_markup=markup)
else :
global table_markup
table_markup = types.InlineKeyboardMarkup(row_width=4)
for item in table_id :
item = str(item).replace("(" , "")
item = str(item).replace(")" , "")
item = str(item).replace("," , "")
update_table_info(int(item))
if tables[1] == 1 : None
else : table_markup.add(types.InlineKeyboardButton(f'{item} стол (от {tables[7]} до {tables[8]} человек)' , callback_data = str(item)))
with open(table_image_path, 'rb') as table_img:
bot.send_photo(call.message.chat.id , table_img , caption='?️Выберите стол' , reply_markup=table_markup)
else :
bot.register_next_step_handler(bot.send_message(call.message.chat.id , '?Пожалуйста укажите корректный номер телефона для связи с вами') , add_phone_num)
for item in table_id :
item = str(item).replace("(" , "")
item = str(item).replace(")" , "")
item = str(item).replace("," , "")
if call.data == "" + str(item) :
bot.delete_message(call.message.chat.id , call.message.message_id)
global table_reserv
table_reserv = int(item)
bot.register_next_step_handler(bot.send_message(call.message.chat.id , '?️Укажите дату и время для бронирования формате ДД.ММ ЧЧ:ММ \n1-31.1-12 21:00-4:00 \nПример : 21.07 21:30'), table_reservation)
if call.data == "help" :
bot.delete_message(call.message.chat.id , call.message.message_id)
bot.send_message(call.message.chat.id , "?Инстарграм бара : instagram.com/nehabar_kst \n?Связь с администрацией : \n⚠️Сообщить об ошибке : @CaH4eZOV" , reply_markup=markup)
elif call.data == "profile" :
bot.delete_message(call.message.chat.id , call.message.message_id)
update_info(call.message.chat.id)
global profile_markup
profile_markup = types.InlineKeyboardMarkup(row_width=2)
update_name = types.InlineKeyboardButton("✏️Обновить имя" , callback_data='update_name')
add_phone_number = types.InlineKeyboardButton("?Добавить номер телефона" , callback_data='add_phone')
delete_reservation = types.InlineKeyboardButton("?️Удалить бронь" , callback_data='delete_reservation')
back = types.InlineKeyboardButton("?Назад" , callback_data='back')
profile_markup.add(update_name,add_phone_number ,delete_reservation ,back)
if buffer_table == 1 :
bot.send_message(call.message.chat.id , f'??Профиль \n?{user[1]}\n?Ваш персональный ID {user[0]} \n?Номер телефона {user[3]} \n?️Номер стола {tables[0]} \n?️Время и дата {tables[5]} \n?♂️Количество персон {tables[6]}' , reply_markup=profile_markup)
else : bot.send_message(call.message.chat.id , f'??Профиль \n?{user[1]}\n?Ваш персональный ID {user[0]} \n?Номер телефона {user[3]}' , reply_markup=profile_markup)
elif call.data == 'add_phone' :
bot.delete_message(call.message.chat.id , call.message.message_id)
bot.register_next_step_handler(bot.send_message(call.message.chat.id , '?Пожалуйста напишите номер телефона') , update_phon_number)
elif call.data == "update_name" :
bot.delete_message(call.message.chat.id , call.message.message_id)
cursor.execute('UPDATE Users SET username = ? WHERE user_id = ?' , (call.from_user.first_name , call.message.chat.id))
db.commit()
update_info(call.message.chat.id)
bot.send_message(call.message.chat.id , f'??Профиль \n?{user[1]}\n?Ваш персональный ID {user[0]} \n?Номер телефона {user[3]}' , reply_markup=profile_markup)
elif call.data == "delete_reservation" :
bot.delete_message(call.message.chat.id , call.message.message_id)
if buffer_table == 1 :
tbdcursor.execute('UPDATE Tables SET reservation = ? , user_id = ? , name = ? , time = ? , phone_number = ? , persons = ? WHERE table_id = ?' , (0 , 0 , "" , 0 , 0 , 0 , tables[0]))
tbd.commit()
bot.send_message(call.message.chat.id , f'??Профиль \n?{user[1]}\n?Ваш персональный ID {user[0]} \n?Номер телефона {user[3]} \n' , reply_markup=profile_markup)
buffer_table = 0
admin_send_not_reservation()
else : bot.send_message(call.message.chat.id , f'❌У вас нет броней!' , reply_markup=profile_markup)
elif call.data == "back" :
bot.delete_message(call.message.chat.id , call.message.message_id)
bot.send_message(call.message.chat.id , "Пожалуйста выберите действие:" , reply_markup=markup)
elif call.data == "admin_update_tables_photo" :
bot.register_next_step_handler(bot.send_message(call.message.chat.id , '?️Отправьте новое изображение плана столов') , admin_update_tables_photo)
elif call.data == "admin_check_reserv" :
check = 0
bot.delete_message(call.message.chat.id , call.message.message_id)
for item in table_id :
item = str(item).replace("(" , "")
item = str(item).replace(")" , "")
item = str(item).replace("," , "")
update_table_info(int(item))
if tables[1] == 1 :
check = 1
bot.send_message(call.message.chat.id , f'? : {tables[3]} \nID : {tables[4]} \n?️Номер стола : {tables[0]} \n?️Дата и время : {tables[5]} \n?Номер телефона : {tables[2]} \n?♂️Количество человек : {tables[6]}')
else :
None
if check != 1 : bot.send_message(call.message.chat.id , f'❌Броней нет' , reply_markup=admin_markup)
else : bot.send_message(call.message.chat.id , f'Пожалуйста выберите действие:' , reply_markup=admin_markup)
elif call.data == "admin_del_reserv" :
check = 0
bot.delete_message(call.message.chat.id , call.message.message_id)
admin_del_markup = types.InlineKeyboardMarkup()
for item in table_id :
item = str(item).replace("(" , "")
item = str(item).replace(")" , "")
item = str(item).replace("," , "")
update_table_info(int(item))
if tables[1] == 1 :
check = 1
admin_del_markup.add(types.InlineKeyboardButton(f'?️{item} стол ({tables[6]} человек | дата и время {tables[5]})' , callback_data = str(item)+"admin"))
else :
None
admin_del_markup.add(admin_back)
if check != 1 : bot.send_message(call.message.chat.id , f'❌Броней нет' , reply_markup=admin_markup)
else : bot.send_message(call.message.chat.id , "Выберите бронь для удаления" , reply_markup=admin_del_markup)
for item in table_id :
item = str(item).replace("(" , "")
item = str(item).replace(")" , "")
item = str(item).replace("," , "")
if call.data == "" + str(item)+"admin" :
admin_delete_reservation(item)
bot.delete_message(call.message.chat.id , call.message.message.id)
bot.send_message(call.message.chat.id , f'✅Бронь успешно удалена!' , reply_markup=admin_markup)
if call.data == "admin_back" :
bot.delete_message(call.message.chat.id , call.message.message_id)
bot.send_message(call.message.chat.id , "Пожалуйста выберите действие:" , reply_markup=admin_markup)
elif call.data == "admin_edit_spam" :
bot.register_next_step_handler(bot.send_message(call.message.chat.id , f'?Напишите текст для рассылки'), admin_edit_spam_text)
if call.data == "admin_start_spam" :
bot.register_next_step_handler(bot.send_message(call.message.chat.id , f'Подтвердите действие в текстовом виде\n(Да/Нет)'), admin_start_spam)
def add_phone_num(message) :
pattern = r'^\+?[0-9]{11,12}$'
match = re.search(pattern, message.text)
if match:
cursor.execute('UPDATE Users SET phone_number = ? WHERE user_id = ?' , (message.text , message.chat.id))
db.commit()
update_info(message.chat.id)
bot.send_message(message.chat.id , f'✅Номер телефона успешно добавлен!' , reply_markup=markup)
else :
bot.register_next_step_handler(bot.send_message(message.chat.id , f'?Введите корректный номер телефона! \nВ формате : +77772126548'), add_phone_num)
def table_reservation(message) :
pattern = r'(?:0[1-9]|[1-2][0-9]|3[01]).(?:0[1-9]|1[0-2]) (?:21:[0-5][0-9]|22:[0-5][0-9]|23:[0-5][0-9]|00:[0-5][0-9]|01:[0-5][0-9]|02:[0-5][0-9]|03:[0-5][0-9])'
match = re.search(pattern, message.text)
if match:
reservation_info = match.group(0)
tbdcursor.execute('UPDATE Tables SET reservation = ? , user_id = ? , name = ? , time = ? , phone_number = ? WHERE table_id = ?' , (1 , message.chat.id , user[1] , message.text , user[3] , table_reserv))
update_table_info(table_reserv)
bot.register_next_step_handler(bot.send_message(message.chat.id , '?♂️Укажите количество персон') , table_reservation_persons)
else :
bot.register_next_step_handler(bot.send_message(message.chat.id , f'⚠️Пожалуйста , введите дату и время в верном формате ДД.ММ ЧЧ:ММ \n1-31.1-12 20:00-04:00') , table_reservation)
def table_reservation_persons(message):
if int(message.text) < tables[7] or int(message.text) > tables[8]:
bot.send_message(message.chat.id, f'⚠️Недопустимое количество персон!', reply_markup=markup)
else:
try:
tbd.execute('COMMIT')
tbd.execute('BEGIN TRANSACTION')
tbd.execute('UPDATE Tables SET persons = ? WHERE table_id = ?', (message.text, table_reserv))
tbd.commit()
update_table_info(table_reserv)
bot.send_message(message.chat.id, f'✅Вы успешно забронировали стол!', reply_markup=markup)
buffer_table = 1
admin_send_reservation()
except sqlite3.Error as e:
tbd.rollback()
bot.send_message(message.chat.id, f'❌Произошла ошибка при бронировании: {e}', reply_markup=markup)
def update_phon_number(message) :
bot.delete_message(message.chat.id , message.message_id-1)
bot.delete_message(message.chat.id , message.message_id)
pattern = r'^\+?[0-9]{11,12}$'
match = re.search(pattern, message.text)
if match:
cursor.execute('UPDATE Users SET phone_number = ? WHERE user_id = ?' , (message.text , message.chat.id))
db.commit()
update_info(message.chat.id)
bot.send_message(message.chat.id , f'??Профиль \n{user[1]}\n?Ваш персональный ID {user[0]} \n?Номер телефона {user[3]}' , reply_markup=profile_markup)
else : bot.register_next_step_handler(bot.send_message(message.chat.id , f'⚠️Введите корректный номер телефона! \nВ формате : +77772126548'), update_phon_number)
def admin_send_reservation() :
bot.send_message(admin_id, f'✅НОВАЯ БРОНЬ! НОВАЯ БРОНЬ!✅ \n?Имя : {tables[3]} \n?ID : {tables[4]} \n?️Номер стола : {tables[0]} \n?️Дата и время : {tables[5]} \n?Номер телефона : {tables[2]} \n?♂️Количество человек : {tables[6]}')
def admin_send_not_reservation() :
bot.send_message(admin_id, f'❌ОТМЕНА БРОНИ! ОТМЕНА БРОНИ!❌ \n?Имя : {tables[3]} \n?ID : {tables[4]} \n?️Номер стола : {tables[0]} \n?️Дата и время : {tables[5]} \n?Номер телефона : {tables[2]} \n?♂️Количество человек : {tables[6]}')
def admin_delete_reservation(admin_table_id) :
tbdcursor.execute('UPDATE Tables SET reservation = ? , user_id = ? , name = ? , time = ? , phone_number = ? , persons = ? WHERE table_id = ?' , (0 , 0 , "" , 0 , 0 , 0 , admin_table_id))
tbd.commit()
update_table_info(admin_table_id)
def admin_update_tables_photo(message) :
file_id = message.photo[-1].file_id
file_info = bot.get_file(file_id)
file_path = file_info.file_path
downloaded_file = bot.download_file(file_path)
with open('tables_photo.jpg', 'wb') as new_file:
new_file.write(downloaded_file)
bot.send_message(message.chat.id, "✅Картинка успешно загружена!" , reply_markup=admin_markup)
def admin_edit_spam_text(message) :
file_name = "spam_text.txt"
with open(file_name, "w", encoding='utf-8') as file:
file.write(message.text)
bot.register_next_step_handler(bot.send_message(message.chat.id , f'?️Загрузите фотографию'), admin_photo_edit_spam)
def admin_photo_edit_spam(message) :
file_id = message.photo[-1].file_id
file_info = bot.get_file(file_id)
file_path = file_info.file_path
downloaded_file = bot.download_file(file_path)
with open('spam_photo.jpg', 'wb') as new_file:
new_file.write(downloaded_file)
bot.send_message(message.chat.id, "✅Рассылка настроенна!" , reply_markup=admin_markup)
def admin_start_spam(message) :
global text_spam
if message.text == "Да" :
file_name = "spam_text.txt"
with open(file_name, "r", encoding='utf-8') as file:
text_spam = file.read()
dbconnect()
users_id = cursor.execute('SELECT user_id FROM Users').fetchall()
for item in users_id :
item = str(item).replace("(" , "")
item = str(item).replace(")" , "")
item = str(item).replace("," , "")
with open(spam_image_path, 'rb') as spam_img :
bot.send_photo(int(item) , spam_img , caption=""+text_spam)
bot.send_message(message.chat.id , f'✅Расыслка запущена!')
elif message.text == "Нет" :
bot.send_message(message.chat.id , f'❌Рассылка не запущена!')
bot.infinity_polling()