@rollly00

TypeError при повторном нажатии кнопки Telebot + MySQL?

Почему при повторном нажатии на кнопку 'города' для показа вакансии получаю ошибку "Missing 1 required positional argument: 'prooblast'". Ведь аргумент передается в функции Query.

Собственно код:
from logging import exception
import pymysql
import telebot
from telebot import types
bot = telebot.TeleBot("")

db = pymysql.connect(
    host='127.0.0.1',
    user='root', 
    password='12345',
    db='vakansii'
    )
    
cur = db.cursor()
table_value = {}
knowns_ids = []

class Table:
    def __init__(self, first):
        self.first = first
        self.city = None
        self.trebovaniya = None
        self.obyazonosti = None
        self.grafik = None
        self.oklad = None
        self.contacts = None
        self.region = None

@bot.message_handler(commands=['start'])
def region(message):
    markup = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
    markup.add('HR/Рекрутинг', 'Программист', 'Дизайнер')
    msg = bot.send_message(message.chat.id,"Выберите профессиональную область:", reply_markup=markup)
    bot.register_next_step_handler(msg, gorod)

def gorod(message): # prog
    prooblast = message.text
    markup = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True)
    markup.add('Москва', 'Омск','Санкт-Петербург','Назад')      
    msg = bot.send_message(message.chat.id,"Выберите город для поиска вакансий:", reply_markup=markup)
    bot.register_next_step_handler(msg, query, prooblast)

@bot.message_handler(commands=['add'])
def pull(message):
    if message.chat.id in knowns_ids:
        msg = bot.reply_to(message, "Название вакансии:")
        bot.register_next_step_handler(msg, process_first_step)       
    else:
        bot.reply_to(message,"Access denied")

def process_first_step(message):
    chat_id = message.chat.id
    first = message.text
    user = Table(first)
    table_value[chat_id] = user
    msg = bot.reply_to(message, 'Город:')
    bot.register_next_step_handler(msg, process_city_step)

def process_city_step(message):
    chat_id = message.chat.id
    city = message.text
    user = table_value[chat_id]
    user.city = city
    msg = bot.reply_to(message, "Требования:")
    bot.register_next_step_handler(msg, process_trebovaniya_step)

def process_trebovaniya_step(message):
    chat_id = message.chat.id
    trebovaniya = message.text
    user = table_value[chat_id]
    user.trebovaniya = trebovaniya
    msg = bot.reply_to(message, "Обязанности:")
    bot.register_next_step_handler(msg, process_obyazonosti_step)

def process_obyazonosti_step(message):
    chat_id = message.chat.id
    obyazonosti = message.text
    user = table_value[chat_id]
    user.obyazonosti = obyazonosti
    msg = bot.reply_to(message, "График работы:")
    bot.register_next_step_handler(msg, process_grafik_step)

def process_grafik_step(message):
    chat_id = message.chat.id
    grafik = message.text
    user = table_value[chat_id]
    user.grafik = grafik
    msg = bot.reply_to(message, "Оклад:")
    bot.register_next_step_handler(msg, process_oklad_step)

def process_oklad_step(message):
    chat_id = message.chat.id
    oklad = message.text
    user = table_value[chat_id]
    user.oklad = oklad
    msg = bot.reply_to(message, "Контакты:")
    bot.register_next_step_handler(msg, process_contacts_step)

def process_contacts_step(message):
    chat_id = message.chat.id
    contacts = message.text
    user = table_value[chat_id]
    user.contacts = contacts
    msg = bot.reply_to(message, "Область:")
    bot.register_next_step_handler(msg, process_region_step)
        
def process_region_step(message):
    try:
        chat_id = message.chat.id
        region = message.text
        user = table_value[chat_id]
        user.region = region
        sql = "INSERT INTO omsk (Вакансия, Город, Требования, Обязанности, График, Оклад, Контакты, Область) \
                    VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
        val = (user.first, user.city, user.trebovaniya, user.obyazonosti, user.grafik, user.oklad, user.contacts, user.region)
        cur.execute(sql, val)
        db.commit()
        bot.reply_to(message,"Вакансия успешно добавлена")
    except:
        bot.reply_to(message, "Ошибка, попробуйте ещё раз")


@bot.message_handler(func=lambda m: True)
def query(message, prooblast):
    cur.execute(""" SELECT * FROM omsk WHERE `Город`= "{0}" AND `Область` = "{1}" """.format(message.text, prooblast))
    col = [i[0] for i in cur.description]
    for row in cur.fetchall():
        row_dict = {col[index]:value for (index, value) in enumerate(row)}
        dict = '\n'.join('✅ {0}: {1}'.format(key, val) for key, val in row_dict.items())
        bot.send_message(message.chat.id,'{}'.format(dict))
            
if __name__ == '__main__':
    bot.polling(none_stop=True)
  • Вопрос задан
  • 52 просмотра
Пригласить эксперта
Ответы на вопрос 1
Вам следует создавать клавиатуры с callback_data.
InlineKeyboardButton
Создать handler для callbackquery
Где как раз при каждом нажатии кнопки хендлер будет получать тот город, на кнопку которого нажали.
CallbackQuery

В вашем коде функция принимает город лишь единожды, после первого нажатия объект prooblast не откуда взять, т.к. вы вышли из register_next_step_handler из которого вы и передавали prooblast
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы