A
A
AirronBark2021-10-25 14:21:57
Python
AirronBark, 2021-10-25 14:21:57

Why is the user's response not being written to the database?

I am making a telegram bot with a registration function. *UPD: The library used in the project - aiogram
If a new user is offered to register, but the user id is transferred to the database, but other records are not added to the database, such as name, phone number, mail. It does not give any errors, while the bot works, receives messages and responds. I don't understand why the message is not sent to the database. Please help me with this.

mainfile:

db = THEPARALLEL_DB('35thparallelClientBase.db')

class FSMRegistration (StatesGroup):
    cl_name= State()
    cl_phone=State()
    cl_email=State()


@dp.callback_query_handler(text='reg')
@dp.callback_query_handler(text='cansel_1')
async def registration(query: types.CallbackQuery):
    answ_data = query.data
    if answ_data == 'reg':
        if (not db.client_exists(query.from_user.id)):
            await bot.send_message(query.from_user.id, text=f'Хорошо, начнем регистрацию, для начала регистрации напишите: далее')
@dp.message_handler(Text(equals='далее', ignore_case=True), state=None)
async def reg_start(message: types.Message):
    await FSMRegistration.cl_name.set()
    await message.reply('Ваша Фамилия и Имя:')
    if (len(message.text) > 20):
        await message.reply(
            ('Имя и фамилия не должны превышать больше 20 символов'))
    elif '@' in message.text or '/' in message.text or '?' in message.text or '#' in message.text or '$' in message.text or '%' in message.text:
        await message.reply(message.from_user.id, "Вы ввели запрещенный символ")
    else:
        db.add_client(message.from_user.id)
        pass
@dp.message_handler(state="*", commands='отмена')
@dp.message_handler(Text(equals='отмена', ignore_case=True), state="*")
async def cansel_handler(message: types.Message, state: FSMContext, current_state=None):
    current_state * await state.get_state()
    if current_state is None:
        return
    await state.finish()
    await message.reply('Ok!')


@dp.message_handler(state=FSMRegistration.cl_name)
async def set_cl_name(message: types.Message, state:FSMContext):
    async with state.proxy() as data:
        db.set_client_name(message.from_user.id, message.text)
        data['cl_name']=message.text
        await FSMRegistration.next() #Ожидание ответа юзера
        await message.reply("Отлично! Теперь введите Ваш номер моб. телефона:")

@dp.message_handler(state=FSMRegistration.cl_phone)
async def set_cl_phone(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        if (len(message.text) > 12):
            await message.reply(('Слишком много знаков! (не используйте + и другие символы, а также пробелы между цифрами)'))
        elif int(message.text):
            data['cl_phone'] = message.text
            db.set_client_phone(message.from_user.id, message.text)
            await FSMRegistration.next()
            await message.reply("Отлично, остался решающий шаг! Прошу ввести Ваш email:")

@dp.message_handler(state=FSMRegistration.cl_email)
async def set_cl_email(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        if '@' not in message.text and '.' not in message.text:
            await message.reply(
            ('Думаю здесь не хватает собаки(@)'))
        else:
            data['cl_email'] = message.text
            db.set_client_email(message.from_user.id, message.text)
            await message.reply("Спасибо за регистрацию, пора в главное меню!")
            await state.finish()


database:
class THEPARALLEL_DB():
    def __init__(self, database_file):
        """Подключаемся к Базе Данных и сохраняем курсор соединения"""
        self.connection = sqlite3.connect(database_file)
        self.cursor=self.connection.cursor()


    def client_exists(self, user_id):
        """Проверяем есть ли клиент уже в базе данных"""
        with self.connection:
            result = self.cursor.execute("SELECT * FROM 'clients' WHERE 'user_id' = ?", (user_id,)).fetchall()
            return bool(len(result))

    def get_user_id (self, user_id):
        result = self.cursor.execute("SELECT 'id' FROM 'clients' WHERE 'user_id'= ?", (user_id,))
        return result.fetchall()[0]

    def add_client(self, user_id):
        """Добавляем нового клиента в базу"""
        with self.connection:
            return self.cursor.execute("INSERT INTO 'clients' ('user_id') VALUES (?)", (user_id,))

    def set_client_name(self, user_id, client_name):
        with self.connection:
            return self.cursor.execute("UPDATE 'clients' SET 'client_name' = ? WHERE 'user_id' = ?",
                                       (client_name, user_id,))

    def set_client_phone(self, user_id, cl_phone):
        with self.connection:
            return self.cursor.execute("UPDATE 'clients' SET 'Телефон' = ?  WHERE 'user_id' = ?", (user_id, cl_phone,))

    def set_client_email(self, user_id, cl_email):
        with self.connection:
            return self.cursor.execute("UPDATE 'clients' SET 'Email' = ? WHERE 'user_id' = ?", (user_id, cl_email,))

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AirronBark, 2021-10-26
@AirronBark

Thanks everyone. Also helped on StuckOverflow.
Answer on SO
According to the comments and answers changed the code in this way and everything works:

def set_client_name(self, user_id, client_name: str):
        return self.connection.execute("""UPDATE clients SET client_name = ? WHERE user_id = ?""",
                                       (client_name, user_id,)) and self.connection.commit()

M
mcjohnyx, 2021-10-26
@mcjohnyx

In sql you need to make a commit after each change

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question