Search code examples
pythontypestimertelegramaiogram

I want to write a timer for telegram-bot with python. The bot gets "time" from user's msg (str). How can I convert "time" from msg to (int) type?


I wrote this code and I need to get "local time" from user's message (string type).
But I need this like integer to set timer.
There is TypeError in

"local_time = int(msg.from_user.id, msg.text)"

How can I fix it?

from aiogram import Bot, types from aiogram.dispatcher import Dispatcher from aiogram.utils import executor import time
from Config import TOKEN

bot = Bot(token=TOKEN)
dp = Dispatcher(bot)


@dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
    await message.reply("Hi!")


@dp.message_handler(commands=['help'])
async def process_help_command(message: types.Message):
    await message.reply("/timer - set timer")


@dp.message_handler(commands=['timer'])
async def set_timer(msg: types.Message):
    await bot.send_message(msg.from_user.id, text='How many minutes?')
    time.sleep(5)
    local_time = int(msg.from_user.id, msg.text)
    local_time_b = int(local_time * 60)
    await bot.send_message(msg.from_user.id, text='Timer set')
    time.sleep(local_time_b)
    await bot.send_message(msg.from_user.id, text='The timer has worked')

print("Hello")

if __name__ == '__main__':
    executor.start_polling(dp)
local_time = int(msg.from_user.id, msg.text)

TypeError: 'str' object cannot be interpreted as an integer

Solution

  • The int function requires the text as first parameter, the second (optional) is the base (which you need if you Python to interpret the string with a different base - ie binany)

    local_time = int(msg.text)
    

    The msg.text is the user input (it must be a number) which it is casted to int.

    If you process the input via a command handler you need to consider that the text message includes the command ie /start 12.
    One option is to remove the command and obtain the following value(s)

    # remove '/start'
    interval = msg.text[7:]
    local_time = int(interval)
    print(local_time)