ValueError: too many values to unpack
Пишу бота для одобрения/отказа заявок, долгое время не мог понять как внедрить кнопки с причинами отказа. Сейчас добавил, при нажатии на нее получаю ошибку
File handle_approve_reject
action, application_id = call.data.split("_")
^^^^^^^^^^^^^^^^^^^^^^
ValueError: too many values to unpack (expected 2)
Пытался исправить, никак не могу, буду благодарен любой помощи.
@bot.callback_query_handler(func=lambda call: call.data.startswith(("approve_", "reject_")))
def handle_approve_reject(call):
"""Обработчик кнопок Одобрить/Отказать."""
db_connection = sqlite3.connect('applications.db')
db_cursor = db_connection.cursor()
action, application_id = call.data.split("_")
application_id = application_id.strip()
# Get application data from the database
db_cursor.execute("SELECT * FROM applications WHERE id=?", (application_id,))
application_data = db_cursor.fetchone()
if application_data:
context = {
'user_chat_id': application_data[2],
'nickname': application_data[3],
'current_position': application_data[4],
'desired_position': application_data[5],
'status': application_data[8]
}
if action == "approve":
new_status = f"Одобрено by: @{call.from_user.username}"
# Отправляем пользователю сообщение о одобрении заявки
user_chat_id = context['user_chat_id']
bot.send_message(user_chat_id, f"🎉🎊🍾 Ваша заявка на повышение на должность '{context['desired_position']}' одобрена by: @{call.from_user.username}")
elif action == "reject":
new_status = f"Отказано by: @{call.from_user.username}"
# Отправляем пользователю сообщение об отказе заявки
user_chat_id = context['user_chat_id']
# Create inline keyboard with rejection reasons
keyboard = types.InlineKeyboardMarkup(row_width=1)
inline_buttons = [
types.InlineKeyboardButton("Неверный скриншот", callback_data=f"reject_reason_{application_id}_1"),
types.InlineKeyboardButton("Старый скриншот", callback_data=f"reject_reason_{application_id}_2"),
types.InlineKeyboardButton("Неустойка минимального срока для повышения", callback_data=f"reject_reason_{application_id}_3"),
types.InlineKeyboardButton("Недостаточно баллов", callback_data=f"reject_reason_{application_id}_4"),
types.InlineKeyboardButton("Есть активное предупреждение", callback_data=f"reject_reason_{application_id}_5"),
types.InlineKeyboardButton("Есть активный выговор", callback_data=f"reject_reason_{application_id}_6"),
]
keyboard.add(*inline_buttons)
bot.edit_message_text(chat_id=management_chat_id, message_id=call.message.message_id,
text="Выберите причину отказа:", reply_markup=keyboard, parse_mode='MarkdownV2')
return
# Update status in the database
db_cursor.execute("UPDATE applications SET status=? WHERE id=?", (new_status, application_id))
db_connection.commit()
# Edit the message to remove inline buttons and update the status
new_message_text = f"От: {context['nickname']}\n" \
f"Текущая должность: {context['current_position']}\n" \
f"Желаемая должность: {context['desired_position']}\n" \
f"Статус: {new_status}\n"\
f"Причина отказа: "
# Update the message to add the selected rejection reason
selected_reason = get_selected_rejection_reason(call.data) # Implement this function to retrieve the selected reason
new_message_text += selected_reason
bot.edit_message_text(chat_id=management_chat_id, message_id=call.message.message_id,
text=new_message_text, parse_mode='MarkdownV2')
else:
bot.send_message(call.from_user.id, "Извините, произошла ошибка при обработке заявки.")
def get_selected_rejection_reason(callback_data):
# Split the callback data by underscores and take the last part as the reason number
parts = callback_data.split('_')
if len(parts) >= 4: # Check if there are enough parts
reason_number = parts[-1]
reasons = {
'1': "Неверный скриншот",
'2': "Старый скриншот",
'3': "Неустойка минимального срока для повышения",
'4': "Недостаточно баллов",
'5': "Есть активное предупреждение",
'6': "Есть активный выговор",
}
return reasons.get(reason_number, "Неизвестная причина")
else:
return "Ошибка при получении причины отказа"
Источник: Stack Overflow на русском