Home > Software design >  Why is the response from the user not recorded in the database?
Why is the response from the user not recorded in the database?

Time:10-26

Good afternoon for everyone.

I have a telegram bot and I want the bot to register users and enter their answers into the database. But the problem is that it registers the user id, but does not update the record in the database with other user responses (Name, email, phone).

By the way I use aiogram library for creating telegram bot.

This is main cod:

class FSMRegistration (StatesGroup):
    cl_name= State()
    cl_phone=State()
    cl_email=State()
db = THEPARALLEL_DB('35thparallelClientBase.db')
@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'Lest do it! Write: next')
@dp.message_handler(Text(equals='next', ignore_case=True), state=None)
async def reg_start(message: types.Message):
    await FSMRegistration.cl_name.set()
    await message.reply('Write your First and Last name')
    if (len(message.text) > 20):
        await message.reply(
            ('The first and last name must not exceed more than 20 characters'))
    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, "You have entered a forbidden symbol.")
    else:
        db.add_client(message.from_user.id)
        pass

@dp.message_handler(state="*", commands='cansel')
@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("Great! Please write your phone:")

@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(('There are too many symbols in your message'))
        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("Great, one more step behind! Your 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(
            ('Error! You have lost this symbol (@)'))
        else:
            data['cl_email'] = message.text
            db.set_client_email(message.from_user.id, message.text)
            await message.reply("Succses, Thank You!")

            await state.finish()

I use sqllite3 for datebase:

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 'Phone' = ?  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,))

CodePudding user response:

You are using the wrong cursor in the context manager. The correct would be:

with self.connection:
    self.connection.execute("INSERT INTO 'clients' ('user_id') VALUES (?)", (user_id,))

You can also open a new cursor on the query:

with contextlib.closing(self.connection.cursor()) as cursor:
    cursor.execute(...)
  • Related