我想用 python 为电报机器人写一个计时器。机器人从用户的消息 (str) 中获取 "time"。如何将 "time" 从 msg 转换为 (int) 类型?

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?

我写了这段代码,我需要从用户的消息(字符串类型)中获取“本地时间”。 但我需要这个整数来设置计时器。 “local_time = int(msg.from_user.id, msg.text)”中存在TypeError。 我该如何解决?

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)

类型错误:'str' 对象不能解释为整数

int 函数需要文本作为第一个参数,第二个(可选)是基数(如果您 Python 解释具有不同基数的字符串,则需要它 - 即 binany)

local_time = int(msg.text)

msg.text 是用户输入(必须是数字),它被转换为 int。

如果您通过命令处理程序处理输入,您需要考虑文本消息包含命令,即 /start 12.
一种选择是删除命令并获取以下值

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

首先

停止在异步函数中使用 time.sleep()。 请改用 await asyncio.sleep()

第二

了解 python 的基础知识。

第三

@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.: 有人请加aiogram标签