D
D
Deduwka2021-11-11 00:51:48
Python
Deduwka, 2021-11-11 00:51:48

How to properly write number input check in python for TG bot?

Good day to all. For a long time I have been trying myself in writing python codes for TG. Here there was a question how to make check of the text entered by the user on numbers. I found the function "isdigit" but I can not bring it to mind, there are many examples on the Internet but none of them work. Here is my code:

def register(message):
    bot.send_message(message.chat.id, "введи числа")
    if message.text.isdigit():
      bot.send_message(message.chat.id, "Данные приняты")
    elif massage.text():
      bot.send_message(message.chat.id, "oops")

The code itself works, but in fact it accepts all messages from the user, and I need only numbers. Where did I make a mistake? Thanks in advance for the hint.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vindicar, 2021-11-11
@Vindicar

try:
  v = int(message.text)
  #на случай если тебе подойдёт не всякое число
  if v < 0 or v > 99: 
    raise ValueError()
except ValueError:
  bot.send_message(message.chat.id, "Не число, или недопустимое число.")
else:
  bot.send_message(message.chat.id, f"Ты ввел число {v}")

S
shurshur, 2021-11-11
@shurshur

What do you think this function should do? It does exactly what is written in it: it sends the message "enter numbers" and then immediately checks the numbers in the user's previous message.
Google examples register_next_step_handler (if it's a telebot) or "library_name finite states machine" in general.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question