skip to Main Content

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

2

Answers


  1. 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)
    
    Login or Signup to reply.
  2. First of all

    Stop using time.sleep() in async functions.
    Use await asyncio.sleep() instead!

    Second

    Learn basics of python.

    Third

    @dp.message_handler(commands=['timer'])
    async def timer_handler(message: Message):
        # get args from message (it's `str` type!) 
        timer_string = message.get_args()
        
        # let's try to convert it to `int`
        try:
            timer = int(timer_string)
        except (ValueError, TypeError):
            return await message.answer("Please set a digit for timer. E.g.: /timer 5")
        
        # success! timer is set!
        await message.answer(f'Timer set for {timer}')
        
        # sleeping (this way, instead of blocking `time.sleep`)
        await asyncio.sleep(timer)
        
        # it's time to send message
        await message.answer("It's time! :)")
    

    P.S.: Someone, please add aiogram tag

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search