V
V
Vadimganin2022-03-31 13:32:36
Python
Vadimganin, 2022-03-31 13:32:36

How to make the code work until the error is fixed?

You need to handle a number input error, that is, if the user enters a number with letters or letters, the number will not pass and will throw a ValueError. I did it, but I want to be able to immediately enter the number again after the error message, until there is no error.

The code:

@bot.message_handler(commands=["put"])
def get_put(message):
    sent_put = bot.send_message(message.chat.id, "Сколько денег(в рублях) ты хочешь положить в копилку?")
    bot.register_next_step_handler(sent_put, put)

def put(message):
        global get_put, balance
        get_put = message.text
        try:
            balance += int(get_put)
            spent_message = "Ты положил " + str(get_put) + "₽" + "\n" + "Теперь в копилке " + str(balance) + "₽"
            bot.send_message(message.chat.id, spent_message, parse_mode="html")
        except ValueError:
            bot.send_message(message.chat.id, "Ошибка! Попробуй написать только число(без букв и символов)")

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Grebnev, 2022-03-31
@Vadimganin

Using isdigit(), as mentioned before, you write a condition, if an error occurs, then return to the same position:

balance = 0
@bot.message_handler(commands=["put"])
def get_put(message):
    sent_put = bot.send_message(message.chat.id, "Сколько денег(в рублях) ты хочешь положить в копилку?")
    bot.register_next_step_handler(sent_put, put)

def put(message):
    global get_put
    get_put = message.text
    if (message.text).isdigit() == False:
        error_message = bot.send_message(message.chat.id, "Ошибка! Попробуй написать только число(без букв и символов)")
        bot.register_next_step_handler(error_message, put)
    else:
        balance += int(get_put)
        spent_message = "Ты положил " + str(get_put) + "₽" + "\n" + "Теперь в копилке " + str(balance) + "₽"
        bot.send_message(message.chat.id, spent_message, parse_mode="html")

And it's probably better to set the balance globally initially, otherwise it will turn out that you re-create it with each replenishment.

A
AVKor, 2022-03-31
@AVKor

That's not how you should do it. Input Validation:

$ python3
Python 3.10.2 (main, Mar  8 2022, 23:56:15) [GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> '123'.isdigit()
True
>>> '123+'.isdigit()
False
>>> '123a'.isdigit()
False

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question