D
D
Dmitry Kasatkin2022-04-20 20:06:18
Python
Dmitry Kasatkin, 2022-04-20 20:06:18

How to insert register_next_step_handler into callback_query_handler?

Tell me how to insert register_next_step_handler into the inline keyboard handler?

Here I call the keyboard
elif message.text == ' Регистрация велосипеда ':
            markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
            btn1 = types.KeyboardButton(' Где наша мастерская? ')
            btn2 = types.KeyboardButton(' Посмотреть прайс на ремонт ')
            btn3 = types.KeyboardButton(' Наши контакты ')
            btn4 = types.KeyboardButton('⏭ Далее ⏭')
            markup.add(btn1, btn2, btn3, btn4)
            bot.send_message(message.chat.id, 'Давайте запишем Ваш байк в базу данных.', reply_markup=markup)
            markup_inline = types.InlineKeyboardMarkup()
            bk1 = types.InlineKeyboardButton(text='Stels', callback_data='Stels')
            bk2 = types.InlineKeyboardButton(text='Forvard', callback_data='Forvard')
            bk3 = types.InlineKeyboardButton(text='Кама', callback_data='Кама')
            bk4 = types.InlineKeyboardButton(text='Урал', callback_data='Урал')
            markup_inline.add(bk1, bk2, bk3, bk4)
            bot.send_message(message.chat.id, 'Выберите модель', reply_markup=markup_inline)
            bot.register_next_step_handler(message, reg)


Here I process callback_query_handler

@bot.callback_query_handler(func=lambda call: True)
def reg(call):
    if call.data == 'Stels':
        chat_id = call.message.chat.id
        conn = sqlite3.connect('db.db')
        cursor = conn.cursor()
        cursor.execute("UPDATE users SET brand = ? WHERE chat_id = ?", (f'{call.data}', f'{chat_id}'))
        conn.commit()
        conn.close()
    elif call.data == 'Forvard':
        chat_id = call.message.chat.id
        conn = sqlite3.connect('db.db')
        cursor = conn.cursor()
        cursor.execute("UPDATE users SET brand = ? WHERE chat_id = ?", (f'{call.data}', f'{chat_id}'))
        conn.commit()
        conn.close()
    elif call.data == 'Forvard':
        chat_id = call.message.chat.id
        conn = sqlite3.connect('db.db')
        cursor = conn.cursor()
        cursor.execute("UPDATE users SET brand = ? WHERE chat_id = ?", (f'{call.data}', f'{chat_id}'))
        conn.commit()
        conn.close()
    elif call.data == 'Кама':
        chat_id = call.message.chat.id
        conn = sqlite3.connect('db.db')
        cursor = conn.cursor()
        cursor.execute("UPDATE users SET brand = ? WHERE chat_id = ?", (f'{call.data}', f'{chat_id}'))
        conn.commit()
        conn.close()
    elif call.data == 'Урал':
        chat_id = call.message.chat.id
        conn = sqlite3.connect('db.db')
        cursor = conn.cursor()
        cursor.execute("UPDATE users SET brand = ? WHERE chat_id = ?", (f'{call.data}', f'{chat_id}'))
        conn.commit()
        conn.close()
    bot.send_message(chat_id, f'Записали!\nИдем дальше.')
    bot.send_message(chat_id, 'Введите серийный номер')


When you run the code, everything goes well until the moment you enter the serial number. coming out
mistake

2022-04-20 21:59:18,309 (__init__.py:615 MainThread) ERROR - TeleBot: "Infinity polling exception: 'Message' object has no attribute 'data'"
2022-04-20 21:59:18,309 (__init__.py:617 MainThread) ERROR - TeleBot: "Exception traceback:
Traceback (most recent call last):
File "C:\VeloUgona.NET\venv\lib\site-packages\telebot\__init__.py", line 611, in infinity_polling
self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout,
File "C:\VeloUgona.NET\venv\lib\site-packages\telebot\__init__.py", line 658, in polling
self.__threaded_polling(non_stop, interval, timeout, long_polling_timeout, allowed_updates)
File "C:\VeloUgona.NET\venv\lib\site-packages\telebot\__init__.py", line 720, in __threaded_polling
raise e
File "C:\VeloUgona.NET\venv\lib\site-packages\telebot\__init__.py", line 680, in __threaded_polling
self.worker_pool.raise_exceptions()
File "C:\VeloUgona.NET\venv\lib\site -packages\telebot\util.py", line 135, in raise_exceptions
raise self.exception_info
File "C:\VeloUgona.NET\venv\lib\site-packages\telebot\util.py", line 87, in run
task(*args, **kwargs)
File "C:/VeloUgona.NET - копия/bot.py", line 320, in reg
if call.data == 'Stels':
AttributeError: 'Message' object has no attribute 'data'


The idea is as follows:
Step 1. The user enters the number
Step 2. The user enters the city
Step 3. The user enters the bike model
Step 4. The user enters the number of the bike Step
5. Save it all to the database

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Krostelev, 2022-04-20
@TKDBOT

I advise you to start by choosing a model is great. This is apparently the only item that is selected by the Inline buttons.
And if the user has a bike not from the proposed set, it will immediately jump off and will not enter too much.
I will take your code as a basis and slightly modify it

...
  elif message.text == ' Регистрация велосипеда ':
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
    btn1 = types.KeyboardButton(' Где наша мастерская? ')
   	btn2 = types.KeyboardButton(' Посмотреть прайс на ремонт ')
    btn3 = types.KeyboardButton(' Наши контакты ')
    btn4 = types.KeyboardButton('⏭ Далее ⏭')
    markup.add(btn1, btn2, btn3, btn4)
    bot.send_message(message.chat.id, 'Давайте запишем Ваш байк в базу данных.', reply_markup=markup)
    markup_inline = types.InlineKeyboardMarkup()
    #  Обратите внимание на callback_data при создании кнопки
    bk1 = types.InlineKeyboardButton(text='Stels', callback_data='bike_model|Stels')
    bk2 = types.InlineKeyboardButton(text='Forvard', callback_data='bike_model|Forvard')
    bk3 = types.InlineKeyboardButton(text='Кама', callback_data='bike_model|Кама')
    bk4 = types.InlineKeyboardButton(text='Урал', callback_data='bike_model|Урал')
    markup_inline.add(bk1, bk2, bk3, bk4)
    bot.send_message(message.chat.id, 'Выберите модель', reply_markup=markup_inline)

#  На случай, если у вас будут еще какие-либо инлайн кнопки,
#  этот хендлер сработает только на тех, у которых callback_data начинается с bike_model
@bot.callback_query_handler(func=lambda call: call.data.startswith('bike_model'))
def reg(call):
    # получаем модель велика
    bike_model = call.data.split('|')[1]
    chat_id = call.message.chat.id
    conn = sqlite3.connect('db.db')
    cursor = conn.cursor()
    cursor.execute(f"UPDATE users SET brand = {bike_model} WHERE chat_id = {chat_id}")
    conn.commit()
    conn.close()
    bot.send_message(chat_id, f'Записали!\nИдем дальше.')
    mes = bot.send_message(chat_id, 'Введите серийный номер')
    bot.register_next_step_handler(mes, serial_number)

def serial_number(message):
  ...

Next comes the standard series of functions with register_next_step_handler

S
soremix, 2022-04-20
@SoreMix Python tag curator

Put awaybot.register_next_step_handler(message, reg) . What is he for?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question