Reloading the changed list in the telegram bot. /restart. pyTelegramBotAPI. Python

I developed a telegram bot to edit a list of services and their prices using ChatGPT, Python, pyTelegramBotAPI. My bot can edit prices and quantities of services, as well as calculate the total price. I added the /restart command, which should restore my service list to its original state after the changes.

The problem is,
that the /restart command does not work as expected. The list of services is not reset, and the bot continues to use the changed list, regardless of the /restart command.

My code is below:

import telebot
from telebot import types

# Ваш токен бота

TOKEN = "TOKEN "

# Словарь, содержащий список услуг и их начальных цен и количеств

services = {
"Услуга 1": {"price_per_unit": 100, "quantity": 0},
"Услуга 2": {"price_per_unit": 65, "quantity": 0},
\#...
}

# Создание бота

bot = telebot.TeleBot(TOKEN)

selected_service = {}

markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
buttons = \[types.KeyboardButton(service) for service in services.keys()\]
markup.add(\*buttons)
markup.add(types.KeyboardButton("Подсчет цены"))

@bot.message_handler(commands=\["start"\])
def start(message):
bot.send_message(
message.chat.id,
"Выберите услугу для редактирования цены и количества:",
reply_markup=markup,
)

@bot.message_handler(commands=\["restart"\])
def restart(message):
chat_id = message.chat.id
selected_service\[chat_id\] = {}  # Очистка выбранной услуги

    bot.send_message(
        chat_id,
        "Бот был обновлен до начального состояния. Все изменения сброшены.",
        reply_markup=markup,
    )

@bot.message_handler(func=lambda message: message.text in services.keys())
def edit_price_or_quantity(message):
chat_id = message.chat.id
service = message.text

    markup = types.ReplyKeyboardMarkup(row_width=2)
    price_button = types.KeyboardButton("Изменить цену")
    quantity_button = types.KeyboardButton("Изменить количество")
    finish_button = types.KeyboardButton("Готово")
    markup.add(price_button, quantity_button, finish_button)
    
    bot.send_message(
        chat_id,
        f"Выберите действие для {service}:",
        reply_markup=markup,
    )
    
    selected_service[chat_id] = service
    bot.register_next_step_handler(message, handle_edit_choice)

def handle_edit_choice(message, selected_action=None):
chat_id = message.chat.id
user_selected_service = selected_service.get(chat_id)

    if user_selected_service:
        selected_action = message.text
        if selected_action == "Изменить цену":
            current_price = services[user_selected_service]['price_per_unit']
            formatted_message = (
                f"Текущая цена для '{user_selected_service}': {current_price} грн\n"
                f"Введите новую цену для '{user_selected_service}':"
            )
            bot.send_message(chat_id, formatted_message)
            bot.register_next_step_handler(message, update_price_or_quantity, user_selected_service, "price_per_unit", selected_action)
        elif selected_action == "Изменить количество":
            current_quantity = services[user_selected_service]['quantity']
            formatted_message = (
                f"Текущее количество для '{user_selected_service}': {current_quantity}\n"
                f"Введите новое количество для '{user_selected_service}':"
            )
            bot.send_message(chat_id, formatted_message)
            bot.register_next_step_handler(message, update_price_or_quantity, user_selected_service, "quantity", selected_action)
        elif selected_action == "Готово":
            start(message)
        else:
            formatted_message = "Некорректный выбор. Выберите действие из клавиатуры."
            bot.send_message(chat_id, formatted_message)
    else:
        formatted_message = "Сначала выберите услугу для редактирования цены."
        bot.send_message(chat_id, formatted_message)

def update_price_or_quantity(message, service, parameter_name, selected_action):
chat_id = message.chat.id
if service in services:
if message.text.isdigit():  # Проверка, является ли текст числовым
try:
new_value = int(message.text)
services\[service\]\[parameter_name\] = new_value

                formatted_message = f"'{parameter_name}' для '{service}': {new_value} грн\n"
                formatted_message += f"Редактировать еще раз '{service}':"
    
                bot.send_message(chat_id, formatted_message)
                bot.register_next_step_handler(message, handle_edit_choice, selected_action)
            except:
                formatted_message = f"Некорректный формат '{parameter_name}'. Введите число.\n"
                formatted_message += f"Редактировать еще раз '{service}':"
                bot.send_message(chat_id, formatted_message)
                bot.register_next_step_handler(message, update_price_or_quantity, service, parameter_name, selected_action)
        elif message.text == "Изменить цену":
            bot.register_next_step_handler(message, handle_edit_choice, "Изменить цену")
        elif message.text == "Изменить количество":
            bot.register_next_step_handler(message, handle_edit_choice, "Изменить количество")
        else:
            formatted_message = "Некорректный ввод. Введите 'Изменить цену' или 'Изменить количество'."
            bot.send_message(chat_id, formatted_message)
    else:
        formatted_message = f"Выберите следующее действие."
        bot.send_message(chat_id, formatted_message)

@bot.message_handler(func=lambda message: message.text == "Подсчет цены")
def calculate_total_price(message):
chat_id = message.chat.id

    services_text = []
    
    for service_name, service_data in services.items():
        price_per_unit = service_data["price_per_unit"]
        quantity = service_data["quantity"]
        service_total = price_per_unit * quantity
    
        if service_total > 0:
            service_formatted = f"{service_name}\n" \
                                f"Количество: {quantity} шт.\n" \
                                f"Цена за шт.: {price_per_unit} грн/шт.\n" \
                                f"Общая стоимость: {service_total} грн\n"
            services_text.append(service_formatted)
    
    total_price_formatted = f"\nОбщая сумма: {sum([service_data['price_per_unit'] * service_data['quantity'] for service_data in services.values()])} грн"
    
    result_message = "\n".join(services_text)
    result_message = f"{result_message}\n\n{total_price_formatted}"
    
    bot.send_message(chat_id, result_message)
    
    if __name__ == "__main__":
        bot.polling(none_stop=True)

I tried using the /restart command in my bot to reset the service selection and start the selection from the beginning. I was hoping that this command would reset the current service selection and allow users to start over with service selection and editing. However, actually when I use the /restart command,
the bot does not reset the selection of the service and proceeds to the selection of the action (price or quantity).

Leave a Comment